Exploring the setTimeout() method in JavaScript with Examples

Do you want to explore and learn what is the setTimeout() method in JavaScript? Read on!

This article will show you how to use the setTimeout() method for delayed code execution, clearing timeouts, and even creating a pauseable timer.

So what are you waiting for? Let’s dive in to master the art of scheduling tasks and animations with this essential JavaScript function.

What is a setTimeout in JavaScript?

The setTimeout() method in JavaScript is used to execute a function after waiting for the specified time interval. It is a method of the global object window and is part of the Web API .

The setTimeout() method can be used to schedule code execution after a specified delay, or to repeat code execution at specified intervals using the setInterval() method .

This can be useful for creating animations, updating the UI, or performing other tasks that need to be done at regular intervals or after a certain amount of time has passed .

Syntax

The syntax for the setTimeout() method is as follows:

setTimeout(function, delay in milliseconds, argument1, argument2,…);

Parameter

function (Required)

Where function is the function to be executed after the timer expires

 delay in milliseconds (Optional)

It is the time in milliseconds that the timer should wait before the specified function or code is executed.

argument1, argument2,... (Optional)

It is the additional arguments which are passed through to the function specified by functionRef.

Return value

The setTimeout() method returns a positive integer value which identifies the timer created by the call to setTimeout().

This value can be passed to the clearTimeout() method to cancel the timeout.

It is important to note that the value returned by setTimeout() is not the actual delay time, but rather an identifier for the timer that can be used to cancel it later if necessary.

How to setTimeout in JavaScript?

Here’s an example of how to setTimeout in JavaScript:

let timeoutID = setTimeout(function() { ✅
console.log('Hi, welcome to Itsourcecode!, after 3 seconds');
}, 3000);

The message “Hi, welcome to Itsourcecode! after 3 seconds” will be logged to the console after a delay of 3 seconds (3000 milliseconds).

Output:

Hi, welcome to Itsourcecode!, after 3 seconds

Here’s the complete example code:

<!DOCTYPE html>
<html>
<body>
<style>
    body {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100vh;
        text-align: center;
    }
</style>

<h1>Welcome to Itsourcecode</h1>
<h2>The setTimeout() Method Example</h2>

<p>Wait for 3 seconds for the greetings:</p>

<h2 id="demo"></h2>

<script>
const myTimeout = setTimeout(myGreeting, 3000); 

function myGreeting() {
  document.getElementById("demo").innerHTML = "Hi, welcome to Itsourcecode, where sourcecode are free!"
}
</script>

</body>
</html>

Output:

How setTimeout works in JavaScript?

The setTimeout() method works in JavaScript by setting a timer that executes a function or specified piece of code once the timer expires.

The method takes two arguments: the first is the function to be executed, and the second is the delay time in milliseconds.

Once the specified delay time has passed, the function is executed. The setTimeout() method returns a positive integer value which identifies the timer created by the call to setTimeout().

As we mentioned earlier, this value can be passed to the clearTimeout() method to cancel the timeout if necessary.

Please be mindful that the setTimeout() method is executed only once. If you need repeated executions, use setInterval() instead.

How to clear setTimeout in JavaScript?

You can clear a setTimeout() in JavaScript by using the clearTimeout() method.

The clearTimeout() method clears a timer set with the setTimeout() method. To clear a timeout, you need to use the ID value returned by the setTimeout() method when you first created the timer.

Here’s an example:

<!DOCTYPE html>
<html>
<head>
    <title>Clear setTimeout Example</title>
</head>
<body>

    <h2>Clear setTimeout Example</h2>

    <p id="demo">Wait for 3 seconds...</p>

    <button onclick="myStopFunction()">Stop the Timeout</button>

    <script>
        const myTimeout = setTimeout(myGreeting, 3000);

        function myGreeting() {
            document.getElementById("demo").innerHTML = "Welcome to Itsourcecode!"
        }

        function myStopFunction() {
            clearTimeout(myTimeout); ✅
        }
    </script>

</body>
</html>

Output:

How to pause setTimeout in JavaScript?

Unfortunately, in JavaScript, you can’t directly pause a setTimeout. But you can make it act like a pause by stopping it with clearTimeout and then starting it again from where it left off.

Here is an example of how you can create a PauseableTimeout class that allows you to pause and resume a setTimeout:

<!DOCTYPE html>
<html>
<head>
    <title>Pause setTimeout Example</title>
</head>
<body>

    <h2>Pause setTimeout Example</h2>

    <p id="demo">Wait for 3 seconds...</p>

    <button onclick="myPauseFunction()">Pause the Timeout</button>
    <button onclick="myResumeFunction()">Resume the Timeout</button>

    <script>
        class PauseableTimeout {
            constructor(callback, delay) {
                this.callback = callback;
                this.remaining = delay;
                this.resume();
            }

            pause() {
                clearTimeout(this.timerId); ✅
                this.remaining -= Date.now() - this.start;
            }

            resume() {
                this.start = Date.now();
                clearTimeout(this.timerId);
                this.timerId = setTimeout(this.callback, this.remaining);
            }
        }

        const myTimeout = new PauseableTimeout(myGreeting, 3000);

        function myGreeting() {
            document.getElementById("demo").innerHTML = "Welcome to Itsourcecode!"
        }

        function myPauseFunction() {
            myTimeout.pause(); ✅
        }

        function myResumeFunction() {
            myTimeout.resume(); 
        }
    </script>

</body>
</html>

Output:

Conclusion

The setTimeout() method in JavaScript is a versatile tool for managing time-based actions in your web applications.

Whether you need to delay code execution, create animations, or schedule regular tasks, understanding how setTimeout() works and how to manipulate it is crucial.

Additionally, you can clear and even simulate pausing timeouts to further enhance your control over timing in JavaScript.

We hope this article has provided you with enough information to help you understand the setTimeout in JavaScript.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Leave a Comment