How can we effectively manage and control these timers?

After working on this inherited code for some time, I've managed to get it functioning properly during the first countdown session. However, I suspect that there may be multiple timers running after a session refresh. I believe I need to use clearInterval() to ensure a stable 20-minute timer, but I'm unsure of the correct way to implement it. Any assistance would be greatly appreciated.

<script type="text/javascript">
    var DoLogout = 1;
    var WarnMills;
    var TimeoutMills;
    var WarnDurationMills;
    var RedirectURL;
    var _timeLeft;

    function StartTimeout(TimeoutValue, WarnValue, WarnDuration, URLValue) {
        TimeoutMills = TimeoutValue;
        WarnMills = WarnValue;
        WarnDurationMills = WarnDuration;
        RedirectURL = URLValue;
        setTimeout(UserTimeout, TimeoutMills);
        setTimeout(WarnTimeout, WarnMills);
    }

    function UserTimeout() {
        if (DoLogout == 1) {
            top.location.href = RedirectURL;
        }
        else {
            DoLogout = 1;
            setTimeout(UserTimeout, TimeoutMills);
            setTimeout(WarnTimeout, WarnMills);
        }
    }

    function WarnTimeout() {
        _timeLeft = (WarnDurationMills / 1000);
        updateCountDown();
        $find('mdlSessionTimeout').show();
    }

    function updateCountDown() {
        var min = Math.floor(_timeLeft / 60);
        var sec = _timeLeft % 60;
        if (sec < 10)
            sec = "0" + sec;

        document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;

        if (_timeLeft > 0) {
            _timeLeft--;
            setTimeout(updateCountDown, 1000);
        }
        else {


            window.location.replace("AdminLogin.aspx");

        }

        if (_timeLeft < (5 * 60)) {
            $find('mdlSessionTimeout').show();
        }
    }

    function PreserveSession() {
        {
            $.ajax({
            type: "POST",
            url: "SessionKeepAlive.asmx/Check",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            cache: false,
            success: checkAuthenticatedOk,
            error: checkAuthenticatedError
        });

    }        
}

function checkAuthenticatedOk() {
    DoLogout = 0;
    _timeLeft = (20 * 60);
    TimeoutMills = (20 * 60 * 1000);
    $find('mdlSessionTimeout').hide();
}

function checkAuthenticatedError() {
    window.location.replace("AdminLogin.aspx");
}

Answer №1

Before calling StartTimeout, it is important to always clear any existing timers.

var userTimerId, alertTimerId;
function StartTimer(...){
    ...
    clearTimeout(userTimerId);
    clearTimeout(alertTimerId);
    userTimerId = setTimeout(UserTimer, TimerMilliseconds);
    alertTimerId = setTimeout(AlertTimer, AlertMilliseconds);
}

Ensure to implement a similar code structure within the UserTimer function as well.

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

"Surprising outcomes when using the splice method on an array

Exploring the functionalities of Array.splice(). deleteCount: A whole number indicating the quantity of old array elements to eliminate. Understood. It seems clear. I aim to extract the final 4 items in the array. I trust that refers to elements? arr. ...

Encountering an issue with Yeoman: jit-grunt error when trying to run

I'm attempting to build an Angular app using Yeoman and Grunt, but I encountered an error when trying to launch the app using 'grunt serve'. grunt serve Running "serve" task Running "clean:server" (clean) task >> 0 paths cleaned. ji ...

Iterate through each row of the PHP array

Hey there, I have two sets of code that I'd like to share with you. The first one is an Ajax snippet: /* Loop and Retrieve Data from Database to Generate a Table */ $(document).ready(function () { $('#btngenerate').click(function(e){ ...

Executing a query in MongoDB to retrieve data from multiple collections simultaneously

Currently, I have two separate collections for different types of products. My goal is to retrieve all documents from both collections that belong to a specific user. I am aware that I could achieve this by running 2 queries for each collection, merging t ...

I am interested in verifying the presence of a file with a .mp4 extension within my directory using Node.js

Here's the situation: I have MP4 files from other people stored on my server and I need to ensure that they are deleted eventually. However, sometimes these files end up lingering around. I'm looking for a solution where the system can detect an ...

Vue and Axios encountered a CORS error stating that the 'Access-Control-Allow-Origin' header is missing on the requested resource

I've encountered the error above while using Axios for a GET request to an external API. Despite consulting the Mozilla documentation, conducting thorough research, and experimenting with different approaches, I haven't made any progress. I&apos ...

Tips for transferring information from a React form into a MySQL database?

Currently, I am venturing into developing my first react application. The backend functionality is operating smoothly; however, I am facing challenges with integrating the input data from a react form into my database. I attempted to use axios for this tas ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...

What sets apart an exception from a promise left unfulfilled?

As I delve into the topic of error handling, I came across an interesting concept in my reading material. The literature explains that if a throw statement occurs within a Promise's catch function, it is considered a rejection. It draws a distinctio ...

Transferring extensive PHP variables to JavaScript

After checking out different strategies for passing data from PHP to Javascript like this and this, I have concerns about the memory and variable size limits in javascript. Currently, I am transferring large chunks of HTML from PHP to Javascript to dynami ...

A dynamically-generated dropdown element in the DOM is being duplicated due to JavaScript manipulation

Currently, I am dynamically adding a dropdown element to the page using javascript. The goal is for this dropdown to modify the properties displayed on a map. However, when attempting to add the element after the map loads, I encounter an issue where the d ...

how can I transfer model values to a dashboard in Rails 5?

I have developed an app that includes an adminlte dashboard. The dashboard is populated with various values obtained by a jQuery file. I am trying to pass module values to the dashboard. For example, the number of users shown in the dashboard should be fet ...

Navigating by a variable float or double in Selenium using Java

Hi all, I am delving into Selenium and getting back into programming after a long break. Apologies in advance if my question isn't clear. I have a webpage with multiple tiles arranged in rows where the height and width can change depending on the wind ...

Removing Blank Spaces from a String Array (JavaScript)

I'm working with a JavaScript array that looks like this: ["X1", " X2", " X3", " X4", " X5", " X6", " X YZ1", " X YZ2", " X7", " X8", " X9"] I need to remove the empty spaces before any letter s ...

Troubleshooting a Compatibility Problem Between Django and JavaScript

I am trying to dynamically insert a variable into a URL within the code snippet provided, but I keep encountering an error. function initializeDataTable(id){ var columnSize = $('table th').size(); $('#table').dataTable({ ...

Divide the child elements into two separate divs evenly

I have a block of HTML code containing <li> elements like the following: <li>one</li> <li>two</li> <li>era</li> <li>jeu</li> <li>iuu</li> <li>iij</li> <li>emu</li> & ...

What is the best way to substitute multiple characters at a specific position in JavaScript?

I'm struggling to figure out how to replace more than one character at a specific index in a string. I attempted using a FOR loop, but it didn't yield the desired results. String.prototype.replaceAt=function(index, replacement) { return this ...

When do you think the request is triggered if JSONP is essentially a dynamic script?

It appears that JSONP requests made using jQuery.ajax are not truly asynchronous, but rather utilize the Script DOM Element approach by adding a script tag to the page. This information was found on a discussion thread linked here: https://groups.google.co ...

express-validator: display a single validation error message for each field

As a newcomer to expressjs and express-validator, I am navigating through setting up a registration form where users need to submit their email address among other details. My current validation rule for the email field using 'express-validator' ...

Vim: Turn off autocomplete when using insert mode key bindings

I've set up a mapping in insert mode to automatically indent brackets: inoremap [;<CR> [<CR>];<Esc>O<Tab> When I use it, the result looks like this (the pipe character represents the cursor): const a = [ | ]; Now, I want ...