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 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Leave a Comment