How to set a timer in JavaScript

In JavaScript, the code is executed asynchronously. However, there are certain in-built functions in JavaScript which allow us to schedule tasks to be executed after a specific amount of time.

svg viewer

The following are the two functions provided by JavaScript for this purpose:

1. setTimeout() method

The setTimeout() method executes a particular function after a specific amount of time has elapsed.

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

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

2. setInterval() method

The setInterval() 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
Copyright ©2024 Educative, Inc. All rights reserved