Morgan Delaney
Morgan Delaney

Reputation: 2439

resetting setInterval in a function, scope is global..?

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.

Upvotes: 0

Views: 5992

Answers (2)

jfriend00
jfriend00

Reputation: 708026

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);

Upvotes: 0

user113716
user113716

Reputation: 322592

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);
});

Upvotes: 6

Related Questions