1. What is a timer JS? It provides some native methods to implement latency to execute a piece of code. Next we will briefly introduce setTimeout: set a timer, execute the timer function or code segment {code...} after the timer expires ...} timeoutId: timer IDfunc: Execution letter after delay... 1. What is a timer?
JS provides some native methods to implement latency to execute a piece of code. Below is a brief introduction
setTimeout: Set a timer to execute the timer function or code segment after the timer expires.
var timeoutId = window.setTimeout(func[, delay, param1, param2, ...]);var timeoutId = window.setTimeout(code[, delay]);
TimeoutId: timer ID
Func: The function executed after the delay
Code: the code string executed after the delay. Similar principles are not recommended.eval()
Delay: the delay time (unit: milliseconds). The default value is 0.
Param1, param2: an extra parameter passed to the latency function. IE9 and later support
setInterval: Call a function or code segment at a fixed interval.
var intervalId = window.setInterval(func, delay[, param1, param2, ...]);var intervalId = window.setInterval(code, delay);
IntervalId: ID of the repeated operation
Func: function for delayed calls
Code: code segment
Delay: delay Time, no default value
setImmediate: Execute the specified function immediately after the browser completely ends the current operation (only implemented in IE10 and Node 0.10 +), similarsetTimeout(func, 0)
var immediateId = setImmediate(func[, param1, param2, ...]);var immediateId = setImmediate(func);
ImmediateId: timer ID
Func: callback
requestAnimationFrame: An API designed specifically to achieve high-performance Frame Animation, but not to specify the delay time, but based on the browser's refresh frequency (FRAME)
var requestId = window.requestAnimationFrame(func);
The above briefly introduces four JS timers, and this article will mainly introduce two commonly used:setTimeoutAndsetInterval.
Ii. Example
// What will be output after the following code is executed? Var intervalId, timeoutId; timeoutId = setTimeout (function () {console. log (1) ;}, 300); setTimeout (function () {clearTimeout (timeoutId); console. log (2) ;}, 100); setTimeout ('console. log ("5") ', 400); intervalId = setInterval (function () {console. log (4); clearInterval (intervalId) ;}, 200); // output: 2, 4, 5
// What will be output in the code block that is executed on the page? SetTimeout (function () {console. log ('timeout') ;}, 1000); setInterval (function () {console. log ('interval')}, 1000); // output timeout once, output interval once every 1 S/* ---------------------------------- * // What is the difference between setInterval and setInterval simulation through setTimeout? Var callback = function () {if (times ++> max) {clearTimeout (timeoutId); clearInterval (intervalId);} console. log ('start', Date. now ()-start); for (var I = 0; I <990000000; I ++) {} console. log ('end', Date. now ()-start);}, delay = 100, times = 0, max = 5, start = Date. now (), intervalId, timeoutId; function imitateInterval (fn, delay) {timeoutId = setTimeout (function () {fn (); if (times <= max) {imitateInterval (fn, delay) ;}}, delay) ;}imitateinterval (callback, delay); intervalId = setInterval (callback, delay );
If yessetTimeoutAndsetIntervalThe two are only different in the number of executions,setTimeoutOnce,setIntervalN times.
And passsetTimeoutSimulatedsetIntervalAndsetIntervalThe difference is:setTimeoutOnlyThe next timer will be called only after the callback is complete., AndsetIntervalRegardless of the execution status of the callback function, whenWhen the specified time is reached, an event for executing callback will be inserted in the event queue.Therefore, when selecting the timer method, considersetIntervalDoes this feature affect your business code?
console.time('immediate');console.time('timeout');setImmediate(() => { console.timeEnd('immediate');});setTimeout(() => { console.timeEnd('timeout');}, 0);
InNode.JS v6.7.0Test foundsetTimeoutRun earlier
What is the result of the code below?
// Question 1 var t = true; setTimeout (function () {t = false;}, 1000); while (t) {} alert ('end '); /* ------------------------------ * // Question 2 for (var I = 0; I <5; I ++) {setTimeout (function () {console. log (I) ;}, 0) ;}/ * -------------------------------- * // Question 3 var obj = {msg: 'obj ', shout: function () {alert (this. msg) ;}, waitAndShout: function () {setTimeout (function () {this. shout () ;}, 0) ;}}; obj. waitAndShout ();
The answer will be answered later.
Iii. Working Principle of JS Timer
Before explaining the answer to the above question, let's take a look at the working principle of the timer. Here we will use the example in How JavaScript Timers Work to explain How the timer works, this figure is a simple schematic.
The number on the left represents the time, in milliseconds. The text on the left represents the waiting operations in the current queue; the blue square indicates the code block being executed. The text on the right shows the asynchronous events that occur during code execution. The figure roughly follows the process below:
At the beginning of the program, a JS Code block starts to be executed. The execution duration is about 18 ms. Three asynchronous events are triggered during the execution, including onesetTimeout, Mouse click event,setInterval
FirstsetTimeoutRun first. The delay time is 10 ms. A mouse event appears later. The browser inserts the click callback function in the event queue.setIntervalRun. After 10 ms,setTimeoutInsert to event queuesetTimeoutCallback
After the first code block is executed, the browser can check which events are waiting in the queue. the browser extracts the code at the top of the queue for execution.
When processing the mouse click callback in the browser,setIntervalAfter checking the arrival delay time again, he will insert an interval callback to the event queue again. A callback will be inserted to the queue after the specified delay time.
After the browser finishes executing the code of the current queue header, it will retrieve the current queue header event again to execute
Here is just a simple description of the timer principle, the actual processing process is more complex than this.
4. Answer questions
Now let's take a look at the answers to the above questions.
Question 1
alertIt will never be executed, because JS is single-threaded and the timer callback will be executed only after the currently executed task is completed.while(t) {}It directly enters the endless loop and keeps occupying the thread. It does not give the callback function execution opportunity.
Question 2
Code output5 5 5 5 5, The same as above, wheni = 0Generate a timer and insert the callback into the event queue. Wait until no task is executed in the current queue.forThe loop is being executed, so the callback is put on hold. After the for loop execution is complete, five callback functions exist in the queue.console.log(i)Because the currentjsThe block-level scope is not used in the code, so the I valueforThe number is 5 after the loop ends, so the code will output 5
Question 3
This problem involvesthisPoint to the problemsetTimeout()The called code runs in an execution environment completely isolated from the function. This causesthisThe keyword will pointwindow(Or global) object,windowObject does not existshoutMethod, so an error is reported. The modification scheme is as follows:
Var obj = {msg: 'obj ', shout: function () {alert (this. msg) ;}, waitAndShout: function () {var self = this; // assign this to the variable setTimeout (function () {self. shout () ;}, 0) ;}}; obj. waitAndShout ();5. Notes
setTimeoutThere is a minimum interval limit. The HTML5 standard is 4 ms and the processing duration is less than 4 ms, but the minimum interval implemented by each browser is different.
Because the JS engine has only one thread, it will force asynchronous events to be queued for execution.
IfsetIntervalThe callback execution time is longer than the specified delay,setIntervalExecute one after another with no interval
thisYou can usebindFunctions, variables, and arrow Functions
The above is the details of the Javascript timer instance code. For more information, see other related articles in the first PHP community!