Detailed explanation of javascript timing function

Detailed explanation of javascript timing function

1.1 Overview
        javascript's built-in setInterval() and setTimeout() functions provide timing functions. The former is executed every few seconds, and the latter is executed after a delay. In addition, the javascript built-in clearInterval() function is used to cancel the timer function.
1.2 setInterval() function
definition:
       The setInterval() function can call the function or calculate the expression according to the specified period (in milliseconds), and use the clearInterval() function to cancel the periodic method call.
Syntax:
        var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
        var intervalID = window.setInterval(code, delay);
Parameter details:
intervalID —— The unique identifier of this repeated operation, Can be passed as a parameter to clearInterval().
Func - a function that is called repeatedly. 
code - A string of code to be executed repeatedly (using this syntax is not recommended for the same reasons as eval()).
delay - the number of milliseconds to delay each time.
Note: Internet Explorer does not support the ability to pass extra parameters to the defer function in the first syntax.
Example:
var fn = function () {
    alert("fn() function was executed");
}
setInterval(fn,1000);//The window pops up every 1min

Note: If the popup window is not closed after the first execution, the function will not be executed in the next second. The reason for this phenomenon is that javascript is a single-threaded environment and is blocked.
1.3 setTimeout() function
definition:
        setTimeout() calls a function or executes a code fragment after the specified delay time. Use the clearTimeout() function to cancel the delay call set by the setTimeout() method.
Syntax:
        var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
        var timeoutID = window.setTimeout(code, delay);
Parameter details:
timeoutID —— the digital ID of the delay operation, Can be passed as a parameter to clearTimeout().
func – a function to execute after delay milliseconds.
code - code to execute after delay milliseconds (using this syntax is deprecated for the same reasons as eval()).
delay - The number of milliseconds to delay.
Note: Internet Explorer does not support the ability to pass extra parameters to the defer function in the first syntax.
Example one:
setTimeout(function() {
console.log(1);
}, 1000); //Print 1 after a delay of 1min
or setTimeout("console.log(1);", 1000); //deprecated syntax

Example two:
setTimeout(function() {
console.log(1);
}, 0);
console.log(2);
//The execution result is: first output 2, then output 1.

Note: The reason for this phenomenon is that the code in SetTimeout() will only be executed when the event queue is empty.
1.3 clearInterval() function
syntax:
        window.clearInterval(intervalID); // intervalID is the return value of setInerval() and is the unique identifier of this setInerval() function.
Note: Use clearInterval(Method); to clear, often can not stop immediately.
Example one:
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Instance</title>
</head>
<body>
<div id="clock"></div>
<button id="btn"></button>
<script>
    function Clock(clockDiv){
        this.clockDiv=clockDiv;
        this.getCurrentDate=function(){
            var currDate=new Date();
            var currDateTime=currDate.getFullYear()+"-"+(currDate.getMonth()+1)+"-"+currDate.getDate()+" "+currDate.getHours()+":"+currDate.getMinutes()+":"+currDate.getSeconds();
            this.clockDiv.innerHTML=currDateTime;
        }
    }
    var clockDiv=document.getElementById("clock");
    var clickObj=new Clock(clockDiv);
    var intervalId=window.setInterval(function () {
            clickObj.getCurrentDate();
    },1000);
    document.getElementById("btn").onclick=function(){
        window.clearInterval(intervalId);
    }
</script>
</body>
</html>

Example two:
//define calculator global variable
var pageTimer =;
//assignment simulation
pageTimer["timer1"] = setInterval(function(){},2000);
pageTimer["timer2"] = setInterval(function(){},2000);
//Clear all method
for(var each in pageTimer){
    clearInterval(pageTimer[each]);
}
// Violent clear
for(var i = 1; i < 1000; i++) {
    clearInterval(i);
}

Analysis: In fact, the method of brute force clearing is not advisable. It is only used when it has to be used. In IE, the return value of the timer is an 8-digit number under IE, such as: 248147094, and the starting value cannot be determined, while Chrome and firefox The following is a single-digit number starting from 1. The general project still recommends the first one, and the first one has good scalability.
1.5 clearTimeout() function
syntax:
        window.clearTimeout(settimeoutID); //settimeID is the return value of setTimeout(), which is the unique identifier of this setTimeout() function.
1.4 Using the setTimeout() function to optimize the setInterval() function
        Generally, the setInterval() function is not used, but the setInterval() function is replaced by the delayed recursion of the setTimeout() function. The setInterval() function can create a stack of callbacks, especially when the time is short.
Optimization scheme one:
var timeout = false; // start and close buttons  
function time() {
    if(timeout) return;
    console.log(1);
    setTimeout(time,1000);
}
time();

Optimization plan two:
var fn = function () {
console.log(1);
setTimeout(fn, 1000)
}
fn();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326446105&siteId=291194637