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 u
I was misunderstanding the clearTimeout function. I thought the callback (calback in setTimeout(...)) would be executed immediately after clearTimeout is called. But the callback is not executed after clearTimeout is called...
The working JS code is,
var array = [1,2,3,4,5,6,7];
var timer;
var i=0;
function execute(){
timer = setTimeout(function () {
alert(array[i]);
i++;
if (array.length > i){
execute();
}
}, 1000);
}
$('document').ready(function(){
$('#loop_controler').click(function(){
if ($(this).text() == 'pause'){
clearTimeout(timer);
$(this).text('resume');
} else {
execute();
$(this).text('pause');
}
});
execute(array,0);
});