setTimeout / clearTimeout problems setTimeout / clearTimeout problems jquery jquery

setTimeout / clearTimeout problems


You need to declare timer outside the function. Otherwise, you get a brand new variable on each function invocation.

var timer;function endAndStartTimer() {  window.clearTimeout(timer);  //var millisecBeforeRedirect = 10000;   timer = window.setTimeout(function(){alert('Hello!');},10000); }


The problem is that the timer variable is local, and its value is lost after each function call.

You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:

var endAndStartTimer = (function () {  var timer; // variable persisted here  return function () {    window.clearTimeout(timer);    //var millisecBeforeRedirect = 10000;     timer = window.setTimeout(function(){alert('Hello!');},10000);   };})();


That's because timer is a local variable to your function.

Try creating it outside of the function.