setTimeout()
setTimeout()
is a function serviced globally by the window object provided by the user’s browser. It allows users to execute callbacks after a period of time expressed in milliseconds.
Syntax
setTimeout()
is capable of receiving multiple parameters where the first is a callback function. The second parameter receives a number that represents the time in milliseconds (1s = 1000ms), which defines the time needed for the callback to execute. The third parameter onwards will be the parameters that the callback function would take in case arguments are defined within the callback.
Below are some examples of how setTimeout()
is composed:
setTimeout(callback)
setTimeout(callback, delay)
setTimeout(callback, delay, param)
Example 1
The following example uses the setTimeout()
function to set a timer to execute the sayHello()
function:
// Defining the functionfunction sayHello() {console.log('Hello from Codecademy');}// Calling the function using setTimeout.setTimeout(sayHello, 4000);
The output will be displayed after 4 seconds:
Hello from Codecademy
Example 2
The following example uses arrow functions. Instead of declaring the function using the keyword function
, it is created using () =>
.
// Defining the functionsetTimeout(() => {console.log('Hello World from Codecademy');}, 2000);
The output from the arrow function will be displayed after 2 seconds:
Hello World from Codecademy
Codebyte Example
In the following code example, setTimeout()
is used to call the sayHello()
function after 3 seconds.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours