JavaScript Timing Events


Timing Events

The window object lets you run code at specific time intervals.

These specific periods of time are known as timing events.

The main techniques for using JavaScript are:

  • setTimeout(callbackFunction, delayInMilliseconds)
    Runs a function after a specified time delay.

  • The code setInterval(function, milliseconds) is similar to setTimeout(), but it keeps running the function repeatedly after a specified time interval in milliseconds.

The setTimeout() and setInterval() are two ways to do things with the HTML DOM Window object.


The setTimeout() Method

window.setTimeout(function, milliseconds);

You can use the setTimeout() method without adding the "window" prefix.

The initial element is a task that needs to be carried out.

The second value shows how many milliseconds to wait before carrying out the action.


How to Stop the Execution?

The clearTimeout() function halts the running of the function identified in setTimeout().

window.clearTimeout(timeoutVariable)

You can write the clearTimeout() method without using "window" before it.

The function clearTimeout() cancels the action set by setTimeout().

myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);

If you haven't run the function yet, you can make it stop running by using the clearTimeout() method.


The setInterval() Method

The setInterval() function makes a specific task happen repeatedly at regular intervals.

window.setInterval(function, milliseconds);

You can use the setInterval() method without typing "window" before it.

The initial parameter represents the function that will run.

The second number tells how much time passes between each time something happens again.

This example runs a function named "myTimer" every second, similar to a digital watch.

In one second, there are 1000 milliseconds.


How to Stop the Execution?

The clearInterval() function halts the running of a function that was set to repeat at intervals using the setInterval() method.

window.clearInterval(timerVariable)

The clearInterval() method can be used without adding "window" before it.

The clearInterval() function stops the repetition set by the variable obtained from setInterval().

let myVar = setInterval(function, milliseconds);
clearInterval(myVar);