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

How to use setInterval function in Javascript?

Guanhui
Release: 2020-06-24 17:42:51
Original
4538 people have browsed it

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!");
}
Copy after login

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;
}
Copy after login

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);
}
Copy after login

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 + '%'; 
    }
  }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template