There are three built-in JavaScript functions that we could use for deferred and optionally repeated execution of functions.
window.requestAnimationFrame(callback)
asks the browser to perform an animation based on the function supplied as the argument. This callback function is invoked before the screen is repainted.
Here's how window.requestAnimationFrame(callback) could be used to move the content div horizontally in our sample page from a previous set of slides:
let pos = 0;
window.requestAnimationFrame(animate);
function animate() {
console.log('I am being animated!')
const c = document.getElementById('content')
c.style.left = pos + 'px';
pos += 1;
window.requestAnimationFrame(animate);
}
Open up a page… and modify the following code in the developer console to animate an element off screen!
let pos = 0;
const ele = document.getElementsByClassName('className')[0];
ele.style.position = 'relative';
ele.style.zIndex = 1000;
function move() {
ele.style.top = pos + 'px';
pos += 1
window.requestAnimationFrame(move);
}
window.requestAnimationFrame(move)
A couple of other timing functions are:
The following example uses set interval to:
setInterval(function() {
const header = document.getElementsByClassName('header')[0];
header.appendChild(document.createElement('h1')).innerText = Date();
}, 2000);
What reasons would you choose to use one timing function (requestAnimationFrame, setTimeout and setInterval) over the others?. This may be obvious, but… →
For animation, use requestAnimationFrame because:
Maybe setInterval, setTimeout… when you need to specify the timing of a function call (though may be unreliable based on throttling!)