Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

timer
javascript
settimeout()
setinterval()

How to set a timer in JavaScript

Educative Answers Team

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 this method:

Clicking on the button will result in the execution of the setAlert() function which will display a pop-up on the screen every 5 seconds.

  • HTML

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 setTimeout() method, let’s implement it:

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

  • HTML

RELATED TAGS

timer
javascript
settimeout()
setinterval()
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring