A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-settimeout-method/ below:

JavaScript setTimeout() Method - GeeksforGeeks

JavaScript setTimeout() Method

Last Updated : 23 Jul, 2025

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

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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4