1. Code
  2. Coding Fundamentals

Timing Events in JavaScript: setTimeout and setInterval

Scroll to top
Read Time: 4 min

JavaScript timing events are used to run code at a specific time or after a specific period of time. These events are frequently used in web development for animations, slide presentations, and other dynamic features that call for updates or changes over time.

The window object, which offers the setTimeout and setInterval methods for scheduling events, is in charge of controlling JavaScript timing events. In JavaScript, the unit of time measurement for timing events is milliseconds, which provides a good balance between precision and practicality. 1000 milliseconds represents one second, 2000 milliseconds represents two seconds, and so on.

Delayed Events With the setTimeout Function

The setTimeout function is used to execute a piece of code after a predetermined amount of time. This function's syntax is as follows:

setTimeout(function, milliseconds);

This executes a function, after waiting for a specified number of milliseconds.

The first parameter is a function to be executed. The second parameter specifies how many milliseconds to wait before execution. If, for example, you want a message saying "Hey there" to pop up on the screen after three seconds, this is how the code would look: 

<button onclick="setTimeout(timingFunction, 3000)">Click Me!</button>

function timingFunction() {
    alert('Hey there');

Repeated Events With the setInterval Function

The setInterval function is used to execute a piece of code repeatedly at predetermined intervals. This function's syntax is as follows:

setInterval(function, milliseconds);

The first parameter is a function to be executed. The second parameter specifies the interval between each execution. Let's build a simple digital clock that displays the current time to demonstrate this. The clock executes the function digitalClock every one second, just like how a digital watch works.

Clearing Timing Events

We might at some point want to stop a function from running after it has run a few times or for a specified period of time. To stop timed execution, prefix clear to the timing event function you are working with.

The clearTimeout() function is used to stop the execution of a function specified in the setTimeout() function. The setTimeout() function returns a timing id. You can use this id to clear the timeout later with clearTimeout().

<button onclick="timingID = setTimeout(timingFunction, 3000)">Start</button>

<button onclick="clearTimeout(timingID)">End</button>

function timingFunction() {
  alert("Hey there");

If you click the Start button, it waits for three seconds before the "Hey there" message is alerted. If you happen to click the End button before those three seconds are up, it stops the function from being executed.

Similarly, the clearInterval() function is used to stop the execution of a function specified in the setInterval() function. Just like for setTimeout(), it uses the timer id returned from the setInterval() function as an argument.  To demonstrate this, we'll add a stop button to the digital clock example above.

The clock starts working once the page is loaded, but when you click the Stop time button, it stops. 

Importance of Clearing the Timing Event Functions

When using timing events in JavaScript, it's crucial to keep in mind that the events must be cleared using the clearTimeout() or clearInterval() function for the following reasons:

To Prevent Memory Leaks

A reference to the function you want to run is stored in memory when you set a timeout or interval in JavaScript. When a timeout or interval is no longer required, you should remove the reference from memory to avoid memory use from increasing. Performance problems may eventually result from this, especially if you're dealing with a lot of data.

To Prevent Unexpected Code Behavior

If you have an interval that refreshes the UI every second but doesn't clear it when the user navigates away from the page, the interval will keep firing even when the user is no longer viewing the page. 

By calling clearTimeout() or clearInterval(), you can cancel the outstanding timer and prevent these issues from occurring. This helps to avoid memory leaks and unexpected behavior while ensuring that your code is effective and predictable.

Example Project Combining Both Timing Events

Here's a little project to demonstrate the two main JavaScript timing events with more advanced functionality. This is a simple webpage that uses setInterval() to display a random number every second and setTimeout() to stop the display after 20 seconds.

Here are a few ideas for other little learning projects you could try to sharpen your skills with the interval and timeout functions:

  • countdown timer
  • random quote generator
  • slideshow animation
  • JavaScript quiz game with timer


Timing events in JavaScript are a useful tool for web developers, enabling them to create dynamic and interactive webpages. The setTimeOut() and setInterval() functions offer a simple approach for scheduling code execution at a particular time or interval. These functions can be used to make a slideshow, animations, and other interactive elements that need to be updated or changed over time. 

Post thumbnail generated with OpenAI's DALL-E 2.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.