The timer

The setInterval() function can call a function repeatedly, with a fixed interval between calls.

setInterval(function() {
// This function will be called automatically at regular intervals
},2000Milliseconds);Copy the code

Case presentation

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, <title>Document</title> </head> <body> <script> var a = 0; setInterval(function(){ console.log(++a); }, 2000); </script> </body> </html>Copy the code

Parameters of a function

The setInterval() function can accept the 3rd and 4th….. Parameters, which will be passed to the function in order.

setInterval(function(a,b) {
// This function will be called automatically at regular intervals
},2000In milliseconds,88.66Corresponding to a, b);Copy the code

Named functions take function arguments

function fun(){
    console.log(++a);
 };
 setInterval(fun,1000);
Copy the code

Clear timer

The clearInterval() function clears a timer

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <h1 id="info">0</h1> <button ID =" bTN1" Id ="btn2"> </button> <script> var oInfo= document.getelementbyid ('info'); var oBtn1 = document.getElementById('btn1'); var oBtn2 = document.getElementById('btn2'); var a=0; // Set the global timer. Obtn1. onclick = function(){// To prevent timer stacking, You should clear the timer before setting it. ClearInterval (timer) // Change the value of the global timer variable to a timer entity timer = setInterval(function(){oinfo.innertext = ++a; }, 1000); }; oBtn2.onclick = function(){ clearInterval(timer); }; </script> </body> </html>Copy the code

decelerator

The setTimeout() function sets a delay timer that executes once the specified time is up. Do not repeat the execution.

setTimeout(function() {
// This function will be executed once after 2 seconds},2000);
Copy the code

Clear delay unit

The clearTimeout() function clears the delayer, much like clearInterval()

Case presentation

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, > <title>Document</title> </head> <body> <button id="btn1" Id ="btn2"> </button> <script> var oBtn1 = document.getelementByid ('btn1'); var oBtn2 = document.getElementById('btn2'); var timer; Obtn1. onclick = function(){timer = setTimeout(function(){alert(' hello '); }, 2000); }; oBtn2.onclick = function(){ clearTimeout(timer); } </script> </body> </html>Copy the code

Get to know asynchronous statements

SetTimeout () and setInterval() are both asynchronous statements