Delay Code Execution Using setTimeout

Sometimes in JavaScript, you may want to pause or delay code execution for a few seconds. The easiest way to do this is by using the built-in setTimeout() function. This method allows you to run a piece of code after a specific amount of time has passed.

In this article, we’ll explain how setTimeout() works, give real examples, and cover common use cases.


What is setTimeout()?

The setTimeout() function lets you run code after a delay, measured in milliseconds.

Syntax:

    setTimeout(function, delay);
  • function: The code you want to run later (usually a function).

  • delay: Time to wait in milliseconds (1 second = 1000 milliseconds).


 Example: Basic Usage

    <button onclick="delayedMessage()">Show Message After 2 Seconds</button>

    <script>
    function delayedMessage() {
    setTimeout(() => {
        alert("Hello! This message was delayed by 2 seconds.");
    }, 2000);
    }
    </script>

What happens:
When you click the button, the alert appears 2 seconds later.


 Common Use Cases for setTimeout()

  • Delay showing a message or modal

  • Wait before redirecting the user

  • Add pause between animations

  • Delay an action after form submission


 Example: Delayed Redirect

    <button onclick="redirectUser()">Go to Website</button>

    <script>
    function redirectUser() {
    alert("Redirecting in 3 seconds...");
    setTimeout(() => {
        window.location.href = "https://example.com";
    }, 3000);
    }
    </script>

What it does:
Shows a message, waits 3 seconds, then takes the user to a new URL.


 Things to Keep in Mind

  • The delay is not exact. It waits at least the specified time, but not always exactly.

  • setTimeout() is asynchronous, meaning the rest of your code continues to run while it waits.

  • You can cancel a timeout using clearTimeout() if needed.


 Bonus: Cancel a setTimeout

    let timerId = setTimeout(() => {
    alert("This will not be shown!");
    }, 3000);

    clearTimeout(timerId); // Cancels the timeout before it runs

Summary

The setTimeout() method is a powerful tool in JavaScript to delay code execution. Whether you're waiting before showing a message, starting an animation, or redirecting users, it’s one of the most useful timing functions in JavaScript.

 Key Points:

  • Delays code using milliseconds

  • Runs code only once after the delay

  • Can be canceled with clearTimeout()

  • Ideal for popups, redirects, and timed effects