killair killair - 5 months ago 34
jQuery Question

javascript clearInterval not working on array function



var intervalHandles = [];

function instanceLoopTimer(url,instance, time, id) {
if (id in intervalHandles) {
clearInterval(intervalHandles[id]);
intervalHandles[id] = 0;
}
intervalHandles[id] = setInterval(function() {
myFuction();
}, time);
}





I created this function so that it can loop itself, the function work perfectly the first time you run but the second time i run with the same values, it seem to go in a infinite loop

I think that the clearInterval is not being triggered so that when i rerun the same instance it goes in the loop, can someone help me out please

Answer

Instead of assigning a value (0) to the intervalHanldes[id] just delete it.

And use else, otherwise you will always create a new interval

var intervalHandles = {}; // should be an object!

function instanceLoopTimer(url,instance, time, id) {	
  if (id in intervalHandles)
    clearInterval(intervalHandles[id])

  intervalHandles[id] = setInterval(myFuction, time);
}

Comments