Background:
When using setInterval or setTimeout we receive a single Id to cancel/clear the actions.
setInterval/setTimeout:
const timeoutId = setTimeout(() => {clearTimeout(timeoutId)}, 1000);
const intervalId = setInterval(() => {clearInterval(intervalId)}, 1000);
requestAnimationFrame: When using raf, for every iteration of step we reset the rafId and we only call cancelAnimationFrame on latest rafId?
let rafId;
function step(timestamp) {
rafId = requestAnimationFrame(step);
console.log(timestamp, rafId)
if(timestamp >= 1000) {
cancelAnimationFrame(rafId);
}
}
rafId = requestAnimationFrame(step);
Question:
How does the cancelAnimationFrame know to close out all previous calls to requestAnimationFrame when the rafId
is constantly being updated?
I have a guess that cancelAnimationFrame works off of a frameId and closes everything behind it.
If thats true, how does it work with multiple requestAnimationFrames
(as they will share a frameIds)
It's true that the id that requestAnimationFrame returns constantly increases by one - but that doesn't really matter. To keep the request 'alive' you need to re-request it inside the callback. Let's see what happens the last time the callback function step is fired:
function step(timestamp) {
console.log("before " + rafId);
rafId = requestAnimationFrame(step);
console.log("after " + rafId);
if (timestamp >= 1000) {
cancelAnimationFrame(rafId);
}
}
rafId = requestAnimationFrame(step);
if you look at the last two lines in your console it's something like:
before 50
after 51
That means the the id returned from the last callback has been 50 and now we're requesting a new animationframe which gets the id 51. This time though our if-condition is true, so it's cancelling the request for id 51. The request for id 50 has been completed as the callback function was called, so there's no need to cancel it.