How to set a timer in JavaScript

Key takeaways:

  • JavaScript provides two main functions for handling timed actions: setTimeout() and setInterval().

  • The setTimeout() is used to execute code after a specified delay.

  • The setInterval() allows us to execute a function repeatedly at set intervals, making it ideal for ongoing tasks such as refreshing content or triggering animations at a regular pace.

  • To stop timers, use clearTimeout() to stop a delayed action from setTimeout() and clearInterval() to halt a recurring action set with setInterval().

In JavaScript, timers manage time-based actions, such as showing messages after a delay, refreshing content periodically, or creating animations. By learning how to set a timer, we can introduce timed actions into our projects, making them more interactive and dynamic. In this Answer, we’ll walk through how to use JavaScript's built-in timer functions: setTimeout() and setInterval().

What are timers in JavaScript?

Timers in JavaScript help us control actions over time, allowing us to:

  • Execute code after a specified delay using setTimeout().

  • Run code at specified intervals using setInterval().

By understanding these two methods, we’ll be able to manage timed actions in our applications.

Setting a one-time timer with setTimeout()

The setTimeout() function allows us to execute a function after a specified delay, measured in milliseconds. This is useful when we want an action to happen just once after a delay.

Syntax

Let’s take a look at the syntax of this method:

setTimeout(myFunction, milliseconds, arg(s));

Parameters

Let’s go over what each of these parameters indicates:

  1. myFunction: The function to execute.

  2. milliseconds: The time in milliseconds after which the function will be executed. This is an optional parameter. By default, the value is set to 0.

  3. arg(s): The parameter(s) to pass to the function, if any.

Return value

The ID of the timer, which is a numeric value, is returned by the function.

Example: Displaying an alert message after a delay

Let’s take a look at how we can implement setTimeout() method:

Clicking on the button will result in the execution of the setAlert() function, which will display a pop-up on the screen after 4 seconds, only once.

  • HTML
The setTimeout() method

In the above code:

  • Line 4: We create a button element with an id of myButton. The onclick attribute is set to call the Function() function when the button is clicked. The button displays the text "Click Me".

  • Lines 7–9: We define a JavaScript function named Function(). When the button is clicked, this function is triggered and starts a timer using setTimeout(). The setTimeout(setAlert, 4000); tells JavaScript to wait 4000 milliseconds (4 seconds) and then execute the setAlert() function. This delays the alert message for 4 seconds after the button is clicked.

  • Lines 11–14: We define a JavaScript function named setAlert() that displays an alert dialog with the message Hello World!. The alert() function in setAlert() creates a pop-up alert box displaying the text Hello World! to the user.

Repeating actions with setInterval()

If we need to repeat an action at regular intervals, the setInterval() method is the tool for the job. This method repeatedly executes a particular function after a specific amount of time. The function will continue to be executed until specified otherwise.

Syntax

Let’s take a look at the syntax of this method:

setInterval(myFunction, milliseconds, arg(s));

Parameters

Let’s go over what each of these parameters indicates:

  1. myFunction: The function to execute.

  2. milliseconds: The time in milliseconds after which the function will be executed repeatedly. This is not an optional parameter. The minimum value of this parameter is 10.

  3. arg(s): The parameter(s) to pass to the function if any.

Return value

The ID of the timer, which is a numeric value, is returned by the function.

Example

Now that we are familiar with the setInterval() method, let’s implement it:

The following code will repeatedly display a pop-up on the screen 5 seconds after the button is pressed.

  • HTML
The setInterval() method

In the above code:

  • Line 4: We create a button element with an id of myButton. The onclick attribute is set to call the myFunction() function when the button is clicked. The button displays the text "Click Me".

  • Lines 7–9: We define a JavaScript function named myFunction(). When the button is clicked, this function is triggered and starts a repeating timer using setInterval(). The setInterval(setAlert, 5000); calls the setAlert() function every 5000 milliseconds (5 seconds). This means that every 5 seconds, setAlert() will be executed, showing a pop-up alert message.

  • Lines 11–14: We define a JavaScript function called setAlert() that displays an alert dialog with a message. The alert() function shows a pop-up message saying Hello World! after every 5 seconds to the user each time it is called.

Stopping timers with clearTimeout() and clearInterval()

To stop a timer, we use the clearTimeout() method for setTimeout() and the clearInterval() method for setInterval(). We need to store the timer ID returned by setTimeout() or setInterval() to be able to clear it.

Syntax

Let’s take a look at their syntax and how to use them.

clearTimeout(timerID);
clearInterval(timerID);

Parameters

Let’s go over what each of these parameters means:

  • timerID: This is the unique identifier (ID) for the timer you want to cancel. It’s the value returned by setTimeout() or setInterval() when the timer is initially created.

Return value

Both clearTimeout() and clearInterval() do not return any value. They simply stop the timer associated with the given timerID.

Example: Stopping a timer

Here’s how to stop a timer after a certain period:

  • HTML
The clearInterval() method

In the above code:

  • Lines 4–5: We create two buttons to start and stop the timers.

  • Line 8: We create a variable to hold the ID of the interval timer so that we can reference and stop it later.

  • Lines 10–14: We define the startTimer() function. This function checks if intervalId is not set, meaning the timer is not currently running. If the timer is not running, setInterval() is used to call the setAlert() function every 5 seconds, and the returned interval ID is stored in intervalId.

  • Lines 16–21: We define the stopTimer() function. This function checks if the timer is running by seeing if intervalId has a value. If the timer is running, clearInterval(intervalId) stop the timer, and intervalId is set to null to indicate that the timer is no longer running.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

Which function would you use to execute a function repeatedly at a regular interval?

A)

setTimeout()

B)

setInterval()

C)

clearTimeout()

D)

clearInterval()

Question 1 of 20 attempted

Conclusion

Timers in JavaScript are a simple yet powerful tool for managing time-based operations. With setTimeout(), we can delay actions, and with setInterval(), we can repeat them at regular intervals. Understanding how to start and stop these timers gives us the flexibility to control time-based behavior in our applications, making them more interactive and responsive.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to make a 1-minute timer in JavaScript?

To create a 1-minute countdown timer, you can use setInterval() to decrease the timer every second until it reaches zero. Here’s an example:

let time = 60; // 1 minute in seconds
const countdown = setInterval(() => {
  console.log(`Time left: ${time} seconds`);
  time--;
  if (time < 0) {
    clearInterval(countdown);
    console.log("Timer complete!");
  }
}, 1000);

How to set a timeout in JavaScript?

To set a timeout, use setTimeout() by specifying the function to run and the delay in milliseconds. For example, to delay an action by 5 seconds:

setTimeout(() => console.log("This message shows after 5 seconds"), 5000);

How to run JavaScript after 1 second?

You can use setTimeout() to delay the execution of a function by 1 second (1000 milliseconds):

setTimeout(() => console.log("This runs after 1 second"), 1000);

This approach is helpful when you need a slight delay before running a function or displaying information to the user.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved