JavaScript provides timer functions for delayed or repeated execution of code in the browser (or event loop in Node.js).
setTimeout(fn, delay)
/ clearTimeout(id)
clearTimeout
const id = setTimeout(() => {
console.log("Executed after 1 second");
}, 1000);
clearTimeout(id); // Cancels execution
setInterval(fn, interval)
/ clearInterval(id)
interval
millisecondsclearInterval
const id = setInterval(() => {
console.log("Runs every 1 second");
}, 1000);
clearInterval(id); // Stops further executions
requestAnimationFrame(callback)
setTimeout(fn, 16)
for animationsfunction animate() {
// update visual state
requestAnimationFrame(animate); // loop
}
requestAnimationFrame(animate);
cancelAnimationFrame(id)
callback(timestamp: DOMHighResTimeStamp)