Simply use `$timeout` inside the `$watch` method in AngularJS to create a chained

My goal is to link two $timeout functions inside a $watch. This $watch monitors user actions, and if any action is detected, both $timeout instances are canceled. Below is the code snippet outlining this scenario.

.run(['$rootScope',  '$location', '$timeout', 'applicationCache', function ($rootScope, $location, $timeout, applicationCache) {
var popupTimer, logoutTimer;
var logoutInterval = 10000, popupInterval = 5000;
$rootScope.$watch(function detectIdle() {
    if($rootScope.userLoggedIn){
        (popupTimer) ? $timeout.cancel(popupTimer) : undefined; // check if timer running, cancel it
        (logoutTimer) ? $timeout.cancel(logoutTimer) : undefined; // check if other timer running, cancel it
        popupTimer = $timeout(function(){
                console.log("show popup");
                logoutTimer = $timeout(function(){
                    console.log("logout");
                    $rootScope.userLoggedIn = false; // set logged In status to false
                    applicationCache.removeAll(); // destroy all session storage
                    $location.path("/login");
                },logoutInterval);
            },popupInterval);
    }
});
}])

The aim here is to display a popup to indicate session expiration after 5 seconds of inactivity, leading to automatic logout after 10 seconds without interaction. Upon interaction, both timers should be reset.

A problem I am encountering is that when there is no user interaction, the inner timeout does not trigger; rather, it gets immediately canceled after initialization. The console only displays "show popup" repeatedly, with "logout" never being printed. It seems like $watch interrupts the execution of the second timer by canceling it prematurely.

To address this issue, what steps can be taken?

Answer №1

To manage the process flow, I suggest utilizing a boolean variable named isInProgress:

.run(['$rootScope',  '$location', '$timeout', 'applicationCache', function ($rootScope, $location, $timeout, applicationCache) {
var popupTimer, logoutTimer, isInProgress= false;
var logoutInterval = 10000, popupInterval = 5000;
$rootScope.$watch(function detectIdle() {
    if($rootScope.userLoggedIn && !isInProgress){
        (popupTimer) ? $timeout.cancel(popupTimer) : undefined; // check if timer running, cancel it
        (logoutTimer) ? $timeout.cancel(logoutTimer) : undefined; // check if other timer running, cancel it
        popupTimer = $timeout(function(){
                console.log("show popup");
                logoutTimer = $timeout(function(){
                    isInProgress = false;
                    console.log("logout");
                    $rootScope.userLoggedIn = false; // set logged In status to false
                    applicationCache.removeAll(); // destroy all session storage
                    $location.path("/login");
                },logoutInterval);
            },popupInterval);
    }
    isInProgress = true;
});
}])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing the performance of MEAN applications under heavy load

As I work on developing an application using the cutting-edge MEAN stack, I have successfully deployed the initial version to a server. This application comprises of a static HTML file (along with CSS and some images) as well as numerous JavaScript files. ...

The object's key values were unexpectedly empty despite containing data

There's an issue with my object - it initially gets key values, but then suddenly loses them all. All the key values become empty and a message appears in the console for the object: "this value was evaluated upon first expanding. it may have ch ...

The issue with GatsbyJS and Contentful: encountering undefined data

Within the layout folder of my project, I have a Header component that includes a query to fetch some data. However, when I attempt to log this.props.data in the console, all I get is 'undefined'. Could someone please point out where I might be m ...

extract information from a document and store it in an array

As I delve into the realm of programming, I find myself grappling with the best approach to extract data from a file and store it in an array. My ultimate aim is to establish a dictionary for a game that can verify words provided by players. Despite my no ...

Is it detrimental to my search engine ranking if I utilize CSS display:none?

Imagine having valuable content that is initially hidden with CSS, and then using javascript to reveal it only when the user clicks on certain links. Even users without javascript enabled can access this content by following the links to a new page where i ...

Unlocking the Secrets of Laravel Blade Integration in a Script File

I am attempting to create a customized store locator application using the guidance provided in this useful tutorial on Google Maps and Laravel 5. While going through various queries related to integrating Google Maps with Laravel, I came across these info ...

Text displaying as actionable icons

In my React project, I am utilizing material-table (https://material-table.com/#/) and have successfully imported the necessary icons. However, when viewing the action bar, the icons are displaying as plain text instead of the Material Icon. import React, ...

Toggle the JavaScript on/off switch

I am attempting to create a toggle switch using Javascript, but I am encountering an issue. Regardless of the class change, the click event always triggers on my initial class. Even though my HTML seems to be updating correctly in Firebug, I consistently ...

"Encountering an error message stating "Cannot access SpreadsheetApp.getUi() within this context" when attempting to execute the

I've encountered an issue while trying to access the UI object in Apps Script. The code I'm using is something I've used before without any problems, but now I'm getting an error message that says "Cannot Call the .getUI()" method from ...

Change PHP code to a JSON file format

I am currently learning Laravel and my current focus is on how to send a JSON file from the back end to the front-end. I intend to utilize this JSON data to generate a graph. Within my model, I have created a function that retrieves values and timestamps ...

Utilize JavaScript to submit the FORM and initiate the 'submit' Event

Hey there! Here's the code I've been working on: HTML : <html> <body> <form enctype="multipart/form-data" method="post" name="image"> <input onchange="test();" ...

How can I switch the visibility of two A HREF elements by clicking on one of them?

Let me break it down for you in the simplest way possible. First off, there's this <a href="#" id="PAUSE" class="tubular-pause">Pause</a> and then we have a second one <a href="#" id="PLAY" class="tubular-play">Play</a> Al ...

Tips for obtaining the retrieved URL from an ajax call

How can I extract only the returned URL from an ajax request? I have tried implementing it like this: $.ajax({ type: "GET", dataType : "jsonp", async: false, url: $('#F ...

Achieving repetitive progress bar filling determined by the variable's value

JSFiddle Here's a code snippet for an HTML progress bar that fills up when the "battle" button is clicked. I'm trying to assign a value to a variable so that the progress bar fills up and battles the monster multiple times based on that value. ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

Navigate through a given value in the event that the property undergoes a name change with each

Exploring an example found on the JSON site, I am facing a situation where I am using an API with JSON data. The property name "glossary" changes for each request made. For instance, if you search for "glossary", the first property is glossary. However, if ...

How to Create a Custom Callback Function for jQuery's .html

I am currently working with the following code: $.ajax({ type: 'GET', url: 'index.php?route=checkout/onepagecheckout/getpaypaldata', dataType: 'json', success: function(json) { ...

A guide on accessing URL query parameters using AngularJS

Is it possible to extract specific URL parameters using AngularJS and then assign their values to textboxes? For instance, a sample URL would be: http://example.com/?param1=value1 I've come across examples involving $location, routing, and services ...

Ways to manage the order of RequestExecutor execution

I have recently developed an intranet site using SharePoint Office 365. Within the master page file, there is a menu bar that utilizes a List to store the URL and name. My goal is to control the visibility of the "Admin" button based on whether the user ...

retrieve the webpage hosted on the server

Seeking to develop a website where users can input a website URL and have it loaded from the server hosting the HTML page, rather than from the user's computer as iframe does by default. I've experimented with various techniques but all seem to l ...