JavaScript Tutorial

BOM Timing (Timing Events)

JavaScript has timing events as it can be executed in time-intervals.

Timing Events

The window object allows execution of code at specified time intervals.

The below two key methods in javascript:

  • setTimeout(function, milliseconds)
    Executes a function, after waiting a specified number of milliseconds.
  • setInterval(function, milliseconds)
    Same as setTimeout(), but repeats the execution of the function continuously.

     Note:- setTimeout() and setInterval() are both methods of the HTML DOM Window object.

setTimeout() Method

window.setTimeout(function, milliseconds);

The window.setTimeout() method can be used without the window prefix.

  • The first parameter is a function to be executed.
  • The second parameter provides the number of milliseconds before execution.

Input:-

Output (Before click):-

Output (After 5 seconds of click ):-

How to Stop the Execution?

The clearTimeout() method used to stops the execution of the function specified in setTimeout().

window.clearTimeout(timeoutVariable)

The window.clearTimeout() method can be used without the window prefix. The clearTimeout() method uses the variable returned by setTimeout():

myVar = setTimeout(function, milliseconds);

clearTimeout(myVar);

If the function has not already been executed, you can stop the execution by calling the clearTimeout() method:

Input:-

Output (Before click):-

Output (After click on “Try me” and before 5 seconds of click on “Stop Execution” to stop the timeout event):-

The setInterval() Method

The setInterval() method is used to repeat a given function at a given time-interval.

window.setInterval(function, milliseconds);

The window.setInterval() method can be used without the window prefix.

  • The first parameter is the function to be executed.
  • The second parameter indicates the length of the time interval between each execution.

This example executes a function called "myIntervalTimer" after every two seconds which increases the number after every two seconds.

Input:-

Output (Increasing the number continuously after every 2 seconds):-

Note:- There are 1000 milliseconds in one second.

How to Stop the Execution?

The clearInterval() method stops the executions of the function specified in the setInterval() method.

window.clearInterval(myVar)

The window.clearInterval() method can be used without the window prefix.

The clearInterval() method uses the variable returned from setInterval():

myVar = setInterval(function, milliseconds);

clearInterval(myVar);

Input:-

Output (Increasing the number continuously after every 2 seconds):-

Output (After Click on Stop Time Interval button the execution will be stopped):-

Go back to Previous Course