Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting a setTimeout

People also ask

Can you clear a setTimeout?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.

How do I reset setTimeout in react?

Clearing setTimeout A setTimeout timer must be cleared and handle properly, otherwise, you may experience adverse side effects in your code. To clear or cancel a timer, you call the clearTimeout(); method, passing in the timer object that you created into clearTimeout().

Which function is used to reset the timeout clock?

timeout.refresh() Sets the timer's start time to the current time, and reschedules the timer to call its callback at the previously specified duration adjusted to the current time.


You can store a reference to that timeout, and then call clearTimeout on that reference.

// in the example above, assign the result
var timeoutHandle = window.setTimeout(...);

// in your click function, call clearTimeout
window.clearTimeout(timeoutHandle);

// then call setTimeout again to reset the timer
timeoutHandle = window.setTimeout(...);

clearTimeout() and feed the reference of the setTimeout, which will be a number. Then re-invoke it:

var initial;

function invocation() {
    alert('invoked')
    initial = window.setTimeout( 
    function() {
        document.body.style.backgroundColor = 'black'
    }, 5000);
}

invocation();

document.body.onclick = function() {
    alert('stopped')
    clearTimeout( initial )
    // re-invoke invocation()
}

In this example, if you don't click on the body element in 5 seconds the background color will be black.

Reference:

  • https://developer.mozilla.org/en/DOM/window.clearTimeout
  • https://developer.mozilla.org/En/Window.setTimeout

Note: setTimeout and clearTimeout are not ECMAScript native methods, but Javascript methods of the global window namespace.


You will have to remember the timeout "Timer", cancel it, then restart it:

g_timer = null;

$(document).ready(function() {
    startTimer();
});

function startTimer() {
    g_timer = window.setTimeout(function() {
        window.location.href = 'file.php';
    }, 115000);
}

function onClick() {
    clearTimeout(g_timer);
    startTimer();
}

var myTimer = setTimeout(..., 115000);
something.click(function () {
    clearTimeout(myTimer);
    myTimer = setTimeout(..., 115000);
}); 

Something along those lines!