tags:

views:

371

answers:

5

I have the following:

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

How can I, via a .click function, reset the counter midway through the countdown?

A: 

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:

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

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

Something along those lines!

Deniz Dogan
+3  A: 

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(...);
bdukes
Thanks, that did the trick
Jason
A: 

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();
}
Frank Krueger
A: 
$(function() {

    (function(){

     var pthis = this;
     this.mseg = 115000;
     this.href = 'file.php'

     this.setTimer = function() { 
      return (window.setTimeout( function() {window.location.href = this.href;}, this.mseg));
     };
     this.timer = pthis.setTimer();

     this.clear = function(ref) { clearTimeout(ref.timer); ref.setTimer(); };
     $(window.document).click( function(){pthis.clear.apply(pthis, [pthis])} );

    })();

});
andres descalzo