0

The problem: When I declare clearInterval()/setInterval() or clearTimeout()/setTimeout() within a function, it does nothing. The reason I must reset it is that the user may click to reset the timer.

What I've tried: I want a function to execute every 3 seconds (hence why I'm using setInterval() vs. setTimeout()), and reset that timer on click. I've tried using setTimeout() by having it clearTimeout() & setTimeout() at the end of every time the function is executed. RESULT: It executes once.

The below code is the same with setInterval. RESULT: It loops and never resets.

// Declare variables as global
var varTimerSpeed = 3000;
var varTimerInterval;
varTimerInterval = setInterval("someFunction()", varTimerSpeed);

function someFunction() {
  // Reset timer
  clearInterval(varTimerInterval);
  varTimerInterval = setInterval("someFunction()", varTimerSpeed);
}

// Call the function
$(".class").live("click",function() { someFunction(); });

I have other things going on in someFunction() that execute properly so I know that the handler for click is working.

Morgan Delaney
  • 2,349
  • 3
  • 20
  • 23
  • although not mentioned in the answer but certainly worth nothing, is that one should get in the habit of passing references to functions for timer functions, as opposed to strings. – thescientist Jul 12 '11 at 23:33
  • Use setTimeout in loop instead of setInteval. http://stackoverflow.com/questions/5479762/will-setinterval-cause-browsers-to-hang – user278064 Jul 12 '11 at 23:51
  • What do you mean by "reset the timer"? Do you mean "stop the timer"? Because your sample code and the two answers already posted both clear (i.e., stop) and then immediately restart the timer and that seems a bit pointless. (Doing so from within the function called by the timer seems even stranger, but that's a secondary issue to understanding what you mean by "reset".) – nnnnnn Jul 13 '11 at 00:50

2 Answers2

6

If you want the someFunction to run at an interval, but have it clear and reset when .class element is clicked, then don't clear the interval inside someFunction.

Just clear and restart it in the click handler.

var varTimerSpeed = 3000;
var varTimerInterval = setInterval(someFunction, varTimerSpeed);

function someFunction() {
  console.log( "someFunction" );
}

$(".class").live("click",function() { 
    clearInterval( varTimerInterval );
    varTimerInterval = setInterval(someFunction, varTimerSpeed);
});
user113716
  • 318,772
  • 63
  • 451
  • 440
0

This slightly modified jsFiddle seems to work fine: http://jsfiddle.net/jfriend00/GgQBu/.

// Declare variables as global
var varTimerSpeed = 3000;
var varTimerInterval = setInterval(someFunction, varTimerSpeed);

function someFunction() {
    // Reset timer
    $("#output").append("...");
    clearInterval(varTimerInterval);
    varTimerInterval = setInterval(someFunction, varTimerSpeed);
}

// Call the function
$(".class").live("click", someFunction);
jfriend00
  • 683,504
  • 96
  • 985
  • 979