Home >Web Front-end >JS Tutorial >How to use setInterval function in Javascript?

How to use setInterval function in Javascript?

Guanhui
GuanhuiOriginal
2020-06-24 17:42:514539browse

The setInterval function in JavaScript is to call a function or calculate an expression according to the specified cycle time. Its syntax is "setInterval(func,ms)". The return value is an ID, which can be passed to "clearInterval" function to cancel execution.

How to use setInterval function in Javascript?

Usage example

You can pop up every three seconds (3000 milliseconds) by calling a named function "Hello":

var myVar;
 
function myFunction() {
    myVar = setInterval(alertFunc, 3000);
}
 
function alertFunc() {
    alert("Hello!");
}

Display the current time (the setInterval() method will execute the function once every second, similar to the watch function):

var myVar = setInterval(function(){ myTimer() }, 1000);
 
function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}

Use clearInterval() to stop the execution of setInterval:

var myVar = setInterval(function(){ myTimer() }, 1000);
 
function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}
 
function myStopFunction() {
    clearInterval(myVar);
}

Use setInterval() and clearInterval() to create a dynamic progress bar:

function move() {
  var elem = document.getElementById("myBar"); 
  var width = 0;
  var id = setInterval(frame, 10);
  function frame() {
    if (width == 100) {
      clearInterval(id);
    } else {
      width++; 
      elem.style.width = width + '%'; 
    }
  }
}

Recommended tutorial: "JavaScript"

The above is the detailed content of How to use setInterval function in Javascript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn