Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Set Timeout

The window object allows execution of code at specified timed intervals. These time intervals are called timing events.

The four key methods to use with JavaScript are:

  • setTimeout(function, milliseconds) executes a function, after waiting a specified number of milliseconds
  • clearTimeout() method clears a timer set with the setTimeout() method
  • setInterval(function, milliseconds) same as setTimeout(), but repeats the execution of the function continuously
  • clearInterval() clears a timer set with the setInterval() method

The setTimeout() method calls a function or evaluates an expression at after a specified interval of time (in milliseconds). This example displays a message after a 10 second delay. You can cancel the countdown by pressing the button.

The setTimeout() and setInterval() functions actually return values which are the ids of the timer. In the event you need to cancel that specific timer, and not all of them, you can reference it by its id.


const ShowMessage = () =>
{
    document.getElementById("demo1").innerHTML = "Hello World!";
    clearInterval(intervalTimerId);
}

const UpdateDisplay = () =>
{
    document.getElementById("demo1").innerHTML = `Showing message in ${countdown}.`;
    countdown--;
}

const StopCountdown = () =>
{
    console.log("Stopping clock...");
    clearInterval(intervalTimerId);
    clearTimeout(timeoutTimerId);
};

let countdown = 10;
let delay = 10000;
let timeoutTimerId = setTimeout(ShowMessage, delay);
let intervalTimerId = setInterval(UpdateDisplay, 1000);

http://www.w3schools.com/jsref/met_win_setinterval.asp

https://www.w3schools.com/jsref/met_win_clearinterval.asp

http://www.w3schools.com/js/js_timing.asp