I'm trying to provide a pause and resume functionality to a loop with recursive calls. I'm using "setTimeout" and "clearTimeout" functions for this...
When a user clicks the button "pause", the timer is set to infinite time (maximum possible). When the user clicks the button "resume", the timeout is supposed to be cleared with "clearTimeout" call. But the timeout is never cleared. What is my mistake?
Thank you in advance..
HTML:
<button id="loop_controler">pause</button>
JS:
var array = [1,2,3,4,5,6,7];
var pause = false;
var timer;
function execute(array,i){
var pauseTime = 0;
if (pause){
pauseTime = 2147483647; //max value for timeout
}
timer = setTimeout(function(){ //set timer
setTimeout(function () {
alert(array[i]); //this timeout gives a constant delay
if (array.length > i) //(just to give enough time to users to click button)
execute(array,i+1);
}, 1000);
}, pauseTime);
console.log('set ' + timer);
}
$('document').ready(function(){
$('#loop_controler').click(function(){
if ($(this).text() == 'pause'){
pause = true;
$(this).text('resume');
} else {
clearTimeout(timer); //clear timer
console.log('clear ' + timer);
pause = false;
$(this).text('pause');
}
});
execute(array,0);
});