setTimeout and setInterval in JavaScript

Just a guy who loves to write code and watch anime.
Search for a command to run...

Just a guy who loves to write code and watch anime.
No comments yet. Be the first to comment.
Qualities that make outstanding builders.

Bipedal vs quadrupedal: how many legs This is about the number of legs the creature walks on. Bipedal. Two legs. Humans, ostriches, T-rex, kangaroos, most fantasy humanoids. Quadrupedal. Four legs. Do

Intro You hear "lerp" and "smoothstep" everywhere in game dev. They sound like math jargon. They're not. Both are small tools that do the same job: smoothly move from one value to another. The problem

What is Kinematics Kinematics is the math field. It's the study of how things move without worrying about forces (which would be dynamics). FK and IK are the two branches: forward kinematics and inver

Intro Textures are usually the biggest cost in a 3D scene. Memory, bandwidth, and load time all get eaten by them. Resizing them is the obvious lever. There's more. This post is about the less obvious

Use Case: You want to execute a piece of code repeatedly at fixed time intervals, such as updating a live clock on your webpage.
JavaScript provides setInterval() for this purpose. It allows you to specify a function to be executed every N milliseconds.
// Update a clock every second
setInterval(function() {
document.getElementById('clock').innerText = new Date().toLocaleTimeString();
}, 1000);
To stop the interval, you can use clearInterval() with the identifier returned by setInterval().
const intervalId = setInterval(yourFunction, 1000);
// When you want to stop the interval
clearInterval(intervalId);
Use Case: You need to execute a function after a delay, such as showing a welcome message a few seconds after a page loads.
For this, setTimeout() is your tool. It executes a function once after a specified delay in milliseconds.
// Show a message after 5 seconds
setTimeout(function() {
alert('Welcome to the site!');
}, 5000);
Similarly, clearTimeout() can be used to cancel the timeout before it occurs, using the identifier returned by setTimeout().
const timeoutId = setTimeout(yourFunction, 5000);
// To cancel the timeout
clearTimeout(timeoutId);
requestAnimationFrame)Use Case: You're creating animations or visual effects that need to run smoothly, adjusting to the browser's refresh rate.
requestAnimationFrame() is designed for such tasks. It tells the browser you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint.
function animate() {
// Update your animation here...
requestAnimationFrame(animate);
}
// Start the animation
requestAnimationFrame(animate);
This method provides a smoother visual experience than setInterval() for animations because it synchronizes with the browser's frame rate and pauses when the user navigates to another browser tab, improving performance and battery life.
Some use cases:
Smooth Animations for Visual Effects: When creating animations, such as moving elements across the screen or fading them in and out, requestAnimationFrame ensures these animations run smoothly. It does this by matching the frame rate to the browser's refresh rate, reducing the chances of animations looking choppy or causing unnecessary CPU load.
Game Loop Implementation: For web-based games, requestAnimationFrame is ideal for implementing the game loop. It allows for smooth and consistent updates to the game's state and rendering, providing a better gaming experience. The function can be recursively called to continuously update game elements and respond to user inputs in real-time.
UI Interactions and Transitions: Complex UI interactions, such as drag-and-drop interfaces or responsive menus with animated transitions, benefit from requestAnimationFrame. It allows for the smooth updating of the UI based on user interaction, ensuring a responsive and tactile feel to web applications without the lag or jitter that might come from less optimized methods.
In conclusion, intervals are best for repeated actions at fixed intervals, timeouts are ideal for delayed single actions, and animation frames offer the smoothest experience for animations.