The Wayback Machine - https://web.archive.org/web/20240717024412/https://www.geeksforgeeks.org/javascript-settimeout-method/
Open In App

JavaScript setTimeout() Method

Last Updated : 22 Jan, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

JavaScript setTimeout() method allows you to schedule the execution of a function or the evaluation of a code after a specified delay.

The setTimeout() method calls a function after several milliseconds. setTimeout() is for executing a function once after a specified delay.

Syntax:

setTimeout(function, delay);

Parameters:

  • function: The function or code snippet to be executed after the specified delay.
  • delay: The time, in milliseconds, to wait before executing the function.

Return Value:

Returns a Number which is the id of the timer. Use this id with clearTimeout(id) to cancel the timer.

Example 1: Here, the greet function will be executed after a delay of 2000 milliseconds (2 seconds).

Javascript




function greet() {
  console.log("Hello, world!");
}
 
// Call the greet function after
// 2000 milliseconds (2 seconds)
setTimeout(greet, 2000);


Output: (Will be printed after 2 sec or 2000ms)

Hello, world!

Example 2: Below is the example of popping an up alert, 2 seconds(2000ms) after the user presses the click me button. 

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport">
    <title>Document</title>
</head>
 
<body>
    <button onclick="setTimeout(gfg, 2000);">
        Press me
    </button>
    <script>
        function gfg() {
            alert('Welcome to GeeksforGeeks');
        }
    </script>
</body>
 
</html>


Output:

Image

Note: We can stop the execution of the setTimeout() function by using a method called as clearTimeout() or by closing the window.

Example 3: Here, we are using a setTimeout() function and stop its execution using the clearTimeout() function before the execution of the setTimeout().

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport">
    <title>Document</title>
</head>
 
<body>
    <p>Press the stop button
        before the alert is shown</p>
    <button onclick="val = setTimeout(gfg, 2000);">
        Press me
    </button>
    <button onclick="clearTimeout(val);">
        Stop Execution</button>
    <script>
        function gfg() {
            alert('Welcome to GeeksforGeeks');
        }
    </script>
</body>
 
</html>


Output:

Image



Similar Reads

JavaScript Program to Pass Parameter to a setTimeout() Method
In this article, we will discuss how to pass parameters to the setTimeout() method in JavaScript. The setTimeout() method is used to delay the execution of a piece of code. This method executes a function, after waiting a specified number of milliseconds. We have different approaches to passing parameters to the setTimeout() method. There are sever
3 min read
JavaScript setTimeout() &amp; setInterval() Method
JavaScript SetTimeout and SetInterval are the only native function in JavaScript that is used to run code asynchronously, it means allowing the function to be executed immediately, there is no need to wait for the current execution completion, it will be for further execution. JavaScript setTimeout() MethodThis method executes a function, after wai
3 min read
How to understand various snippets of setTimeout() function in JavaScript ?
When dealing with JavaScript, there will be times when you wish to run a function after a particular period of time. For this, we use setTimeout(), an asynchronous method that sets a timer, which then executes the function or specified piece of code once the timer expires. In this article, we will be exploring several code snippets on how setTimeou
3 min read
What is setTimeout() function in JavaScript ?
The setTimeout function in JavaScript is a method used to introduce a delay before executing a specified function or code block. It is commonly employed for asynchronous programming and executing tasks after a certain period. It's crucial to understand that the delay setTimeout is not guaranteed to be precise. The specified time represents the mini
1 min read
Difference Between setTimeout & setInterval in JavaScript
JavaScript has both setTimeout and setInterval functions that are used for executing code after a certain delay. However, they differ in how they handle the timing of execution. Understanding their differences is crucial for effectively managing asynchronous operations in our code which is explained below: Table of Content Using setTimeoutUsing set
2 min read
What is the purpose of setTimeout() function in JavaScript ?
In JavaScript, the setTimeout() function is vey good for adding delays or scheduling the execution of a specific function after a certain period. It's a key feature of both browser environments and Node.js, enabling asynchronous behavior in code execution. Whether you're building a web application or a server-side script, setTimeout() offers flexib
2 min read
Node.js Http2ServerResponse.setTimeout() Method
The Http2ServerResponse.setTimeout() is an inbuilt application programming interface of the class Http2ServerResponse within the http2 module which is used to set the duration for a time after which a particular action will take place. Syntax: const response.response.setTimeout(msecs[, callback]) Parameters: This method takes the integer value of d
3 min read
How to wrap setTimeout() method in a promise ?
To wrap setTimeout in a promise returned by a future. We can wrap setTimeout in a promise by using the then() method to return a Promise. The then() method takes up to two arguments that are callback functions for the success and failure conditions of the Promise. This function returns a promise. There can be two different values if the function ca
2 min read
Node.js http.ClientRequest.setTimeout() Method
The http.ClientRequest.setTimeout() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to set the request time out for the client request. Syntax: request.setTimeout(timeout[, callback])Parameters: This method takes the time out value as a parameter in milliseconds, and the second parameter i
2 min read
Node.js http2session.setTimeout() Method
The http2session.setTimeout() is an inbuilt application programming interface of class http2session within http2 module which is used to set the duration for a time after which a particular action will take place. Syntax: const http2session.setTimeout(msecs, callback) Parameters: This method takes the following two parameters as shown below: msecs:
3 min read
three90RightbarBannerImg