jQuery - How to restart setInterval after killing it off with clearInterval? jQuery - How to restart setInterval after killing it off with clearInterval? jquery jquery

jQuery - How to restart setInterval after killing it off with clearInterval?


I think you need to pull the set interval id outside of the function scope.

var refreshIntervalId;$('#leave').click(function () {        refreshIntervalId = setInterval( update, 10000 );        })$('#stay').click(function () {           clearInterval(refreshIntervalId);        })});

Maybe some validation checking on the refreshIntervalId variable also...

if(refreshIntervalId!=null){   // Do something with the interval id}


It's a scope issue. That means that wherever you put the "var" at defines what functions have access to the variable. If you define the variable outside of all of the functions like in Tricker's example, any function in your document has access to that value.

Tricker's example previously posted:

var refreshIntervalId = null;$('#leave').click(function () {    refreshIntervalId = setInterval( "update()", 10000 );})$('#stay').click(function () {   clearInterval(refreshIntervalId);})

Sometimes the whole document doesn't need to have access to the variable, so you want to put it inside of a function.


First of all you can't define a variable in the #leave click function and use it in the #stay click function.

Use it like this:

var refreshIntervalId = null;$('#leave').click(function () {    refreshIntervalId = setInterval( "update()", 10000 );})$('#stay').click(function () {   clearInterval(refreshIntervalId);})