karthick
karthick

Reputation: 12176

request animation frame loop

I came across this code https://gist.github.com/joelambert/1002116 and i thought of playing around with it

I tried to create a loop and stop it

var tick = 0;
var dor = requestInterval(function(){
  tick++;
   console.log("hi", tick)
  if (tick > 10){

     stop();
  }
},300)

function stop(){ 
  console.log("stop")
     clearRequestInterval(dor);
}

But the clearRequestInterval is not clearing the timer. But when i tried to call it from a button's event handler its working. Am I missing something?

I have attached a codepen http://codepen.io/srajagop/pen/KgbbpR

Upvotes: 0

Views: 186

Answers (1)

Nándor Előd Fekete
Nándor Előd Fekete

Reputation: 7098

@Bergi is right that the example code you tried to use is broken, it doesn't support cancelling the interval timer from within the interval function itself. You can work around that by invoking the clearRequestInterval asynchronously:

function stop() {
  console.log("stop");
  window.setTimeout(function() {
    clearRequestInterval(dor);
  }, 0);
}

Or perhaps better, you could fix the example code not to reschedule itself even if it was cancelled from within the interval function.

Upvotes: 1

Related Questions