Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the setInterval () method in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 07:34:32 09月29日 Update

Xiaobian to share with you how to use the setInterval() method in JavaScript, I believe most people still do not know how to use it, so share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!

JavaScript setInterval() method operation practice

The setInterval() method repeats the given function every given time interval.

window.setInterval(function, milliseconds);

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

The first parameter is the function to be executed.

The second parameter is the length of the time interval between each execution.

This example executes the function "myTimer" once per second (like a digital watch).

examples

Display current time:

var myVar = setInterval(myTimer, 1000);

function myTimer() {

var d = new Date();

document.getElementById("demo")[xss_clean] = d.toLocaleTimeString();

}

There are 1000 milliseconds in a second.

How to stop execution?

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

window.clearInterval(timerVariable)

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

The clearInterval() method uses variables returned from setInterval():

myVar = setInterval(function, milliseconds);

clearInterval(myVar);

examples

Similar to the previous example, but we added a "Stop Time" button:

Tags: Methods time functions articles content prefixes parameters examples primary functions not much middle finger between variables most watches buttons numbers more knowledge industry Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Huawei vpn Linux OPPO Reno