-- online Search!

Timers in JavaScript

by kirupa   |   filed under JavaScript 101

Synchronous JavaScript keeps running on its thread until the current work finishes or yields control. A tight loop does not pause to display each intermediate update. That is useful for quick calculations, but it is not the pacing we want for an animation or a delayed response.

We can ask the browser to schedule work for later with setTimeout, setInterval, and requestAnimationFrame. These functions do not interrupt the JavaScript already running on the same thread. Let's look at what each one schedules.

Onwards!

Delaying with setTimeout

The setTimeout function schedules a one-time callback with a requested delay in milliseconds. The delay is not an exact execution deadline: the callback still needs the thread to become available, and browser policies can delay it further. Here is the basic form:

let timeoutID = setTimeout(someFunction, delayInMilliseconds);

Going a bit more example-ish, if we wanted to call a function called showAlert after 5 seconds, the setTimeout declaration would look as follows:

function showAlert() {
  alert("moo!");
}

let timeoutID = setTimeout(showAlert, 5000);

Cool, right? The timeoutID variable stores the handle returned by setTimeout, not the function itself. We can keep that handle to refer to this particular pending timer.

Now, you may be wondering why we would ever want to reference a timer once we've created it. There aren't too many reasons. The only reason I can think of would be to cancel the timer. For setTimeout, that is conveniently accomplished using the clearTimeout function and passing the timeout ID as the argument:

clearTimeout(timeoutID);

If you are never planning on canceling your timer, you can just use setTimeout directly without having it be part of the variable initialization.

Anyway, moving past the technical details on how to use setTimeout, let's talk about when we would commonly use it in the real world. Two words: UI development. When we are doing UI development, deferring some action to a later time is unusually common. Here are some examples that I ran into just in the past month:

  1. A menu slides in, and after a few seconds of the user no longer playing with the menu, the menu slides away.
  2. While waiting for asynchronous work, a timeout can show a message or request cancellation if the operation supports it. It cannot interrupt a synchronous loop on the same main thread; that loop must finish or yield first.
  3. My favorite (and one that I wrote a tutorial about as is well) is where you use the setTimeout function to detect whether users are inactive or idle!

If you do a search for setTimeout on this site or google, you'll see many more real-world cases where setTimeout proves very useful.

Looping with setInterval

The next timer is setInterval. It requests repeated callbacks instead of a single callback. The requested interval is not a guarantee of exact callback or display timing, and the timer continues until it is cleared or its environment ends.

Here is how you would use the setInterval function:

let intervalID = setInterval(someFunction, delayInMilliseconds);

The first argument is the callback and the second is the requested interval in milliseconds. Keep the returned handle when the controller needs to cancel the timer. An interval does not wait for a Promise returned by an asynchronous callback: a slow request can still be pending when another callback starts. If overlap is unwanted, track in-flight work or schedule the next request after completion, including the failure path.

Here is a complete example that requests a drawText callback every two seconds. We update an existing element instead of using document.writeln after page load, which can replace the document:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Show me some text!</title>
</head>

<body>
  <pre id="output"></pre>
  <script>
    let thingToPrint = "";
    
    function drawText() {
      thingToPrint += "#";
      document.getElementById("output").textContent += thingToPrint + "\n";
    }

    let intervalID = setInterval(drawText, 2000);
  </script>
</body>

</html>

If we wish to cancel the looping, we can use the appropriately named clearInterval function:

clearInterval(intervalID);

Its usage is similar to its clearTimeout equivalent. We pass in the ID of the setInterval timer instance that we optionally retrieved while setting up our setInterval in the first place.

For a long time, setInterval was commonly used for JavaScript animations. Dividing a second by a target frame rate gives a requested timer interval, but it does not guarantee that many visible frames:


// A requested interval, not a guarantee of 60 displayed frames per second
setInterval(moveCircles, 1000 / 60);

To see setInterval in action in some other realistic examples on this site itself, check out the bottom of the Creating a Sweet Content Slider article as well as the Creating an Analog Clock article. They both feature setInterval quite prominently!

Animating Smoothly with requestAnimationFrame

Now, we get to one of my favorite functions: requestAnimationFrame. It schedules a callback around a browser rendering opportunity. The browser is also handling layout, input, scripts, and resources, and the available cadence depends on the display and browser. It is not fixed at sixty callbacks or visible frames per second.

For visual updates, this coordination is more appropriate than treating a timer callback as a guaranteed displayed frame. It does not make expensive work free, move the callback off the main thread, or promise that frames will never be dropped. Our callback still has to finish quickly enough for the browser to do its other work.

The way we use this function starts off a bit similar to setTimeout and setInterval:

let requestID = requestAnimationFrame(someFunction);

We do not specify an interval. The browser decides when a rendering opportunity is available and may reduce or pause callbacks in a background tab. Use elapsed time when an animation's speed must remain consistent across changing callback rates.

Anyway, this usage of the requestAnimationFrame function is merely the textbook version. In real life, you'll rarely make a single call to requestAnimationFrame like this. Key to all animations created in JavaScript is an animation loop, and it is this loop that we want to throw requestAnimationFrame at. The result of that throw looks something as follows:

function animationLoop() {
  // animation-related code

  requestAnimationFrame(animationLoop)
}

// start off our animation loop!
animationLoop();

Inside animationLoop, we request another callback rather than calling the function recursively right away. The current invocation can return control to the browser before the next scheduled invocation. Each request schedules one callback; requesting another continues the animation. A costly callback can still delay the page, and a controller should cancel or invalidate pending work when its animation is no longer needed.

To learn more about requestAnimationFrame and its primary use in creating awesome animations, you should check out all the content in the Animations in JavaScript section. In that section, I also dive deeper into requestAnimationFrame beyond the highlights we've looked at here.

Conclusion

If you think that timers fall under a more niche category compared to some of the other more essential things like if/else statements and loops, you would probably be right in thinking that. You can build many awesome apps without ever having to rely on setTimeout, setInterval, or requestAnimationFrame. That doesn't mean it isn't essential to know about them, though. There will be a time when you'll need to delay when your code executes, loop your code continuously, or create a sweet animation using JavaScript. When that time arrives, you'll be prepared...or at least know what to Google for.

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--