The setTimeout() function allows you to execute code once after a specified delay:
setTimeout(function() {
alert("This appears after 2 seconds");
}, 2000);The delay is in milliseconds. 1000 ms = 1 second.
The setInterval() function repeatedly runs a block of code every defined number of milliseconds:
const intervalId = setInterval(() => {
console.log("Repeating every 1 second");
}, 1000);Use the returned timer ID to stop the execution of the timer:
const timeoutId = setTimeout(() => {
console.log("You won't see this.");
}, 5000);
clearTimeout(timeoutId); // Cancels the timeout
clearInterval(intervalId); // Stops the intervallet count = 3;
const countdown = setInterval(() => {
console.log(count--);
if (count < 0) clearInterval(countdown);
}, 1000);requestAnimationFrame instead of setInterval for smoother performanceAsk the AI if you need help understanding or want to dive deeper in any topic