search ]

JavaScript setTimeout() Function: Examples and Usage

The setTimeout() function in JavaScript is used to execute a function after a specified delay. It allows you to delay the execution of code, making it useful for tasks like animations, deferred actions, or timed events.

Basic Usage of setTimeout()

The setTimeout() function takes two parameters: the function to execute and the delay in milliseconds. The syntax of the function is:

setTimeout(function, delay);

Here is an example:

setTimeout(function() {
    console.log('This message is displayed after 2 seconds');
}, 2000);

In this example, the message will be logged to the console after a 2-second delay.

Using Named Functions with setTimeout()

You can also pass a named function to setTimeout().

function showMessage() {
    console.log('This message is displayed after 3 seconds');
}
setTimeout(showMessage, 3000);

Here, the showMessage function is executed after a 3-second delay.

Canceling a Timeout with clearTimeout()

The clearTimeout() function is used to cancel a timeout that was previously established by setTimeout(). When you call setTimeout(), it returns a unique identifier for that timeout. By passing this identifier to clearTimeout(), you can cancel the execution of the function scheduled by setTimeout().

let timeoutID = setTimeout(function() {
    console.log('This message will not be displayed');
}, 4000);

// Cancel the timeout
clearTimeout(timeoutID);

In this example, the timeout is canceled before the message is displayed, so the message is never logged to the console.

Live Example of setTimeout()

The following live example uses setTimeout() to display a message after a 2-second delay when the “Start Timer” button is clicked. If the “Cancel Timer” button is clicked before the timeout completes, the clearTimeout() function stops the timer, and the message “Timer canceled” is displayed instead.

I’ve used the following code to achieve that:

HTML:

<button id="startButton">Start Timer</button>
<button id="cancelButton">Cancel Timer</button>
<div id="message"></div>

JavaScript:

document.addEventListener('DOMContentLoaded', () => {
    let timeoutID;
    const messageDiv = document.getElementById('message');
    const startButton = document.getElementById('startButton');

    startButton.addEventListener('click', () => {
        startButton.classList.add('active');
        timeoutID = setTimeout(() => {
            messageDiv.textContent = 'This message is displayed after 2 seconds';
            startButton.classList.remove('active');
        }, 2000);
    });

    document.getElementById('cancelButton').addEventListener('click', () => {
        clearTimeout(timeoutID);
        messageDiv.textContent = 'Timer canceled';
        startButton.classList.remove('active');
    });
});

Conclusion

The setTimeout() function is a powerful tool in JavaScript for scheduling delayed actions. Understanding how to use it effectively can enhance your ability to create dynamic and responsive web applications. Additionally, the clearTimeout() function provides control over these delayed actions, allowing you to cancel them if needed.

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development