JavaScript timer
JavaScript is an interpreted language (side-compilation side execution), the JS parsing order is from top to bottom, then the compiled task is dropped into an event queue, and then the function within the event starts from top to bottom execution
SetInterval
SetInterval (fn,t); FN is a block of code that executes after an interval of T milliseconds
EXECUTE fn Every t until you clear the timer
When the JS engine reads a setinterval statement, it drops a task into the browser's timed trigger, and then the timed trigger drops a task in the current task queue every T millisecond, and the task content is the code block in FN (with the truth)
var starttime=new Date ();
SetInterval (function () {
Console.log (New Date ()-starttime) + "millisecond");
},1000);
You can see that it's almost 1000 milliseconds each time.
SetTimeout
SetTimeout (fn,t); executes FN After a delay of T milliseconds, except that it only executes once.
var starttime=new Date ();
SetTimeout (function () {
Console.log (New Date ()-starttime) + "millisecond");
},1000);
See here the careful person will find the word async
The timer is asynchronous.
Give us an example.
var fn=function () {
Console.log (123);
}
SetTimeout (fn,1000);
Console.log (567);
You didn't think? 567 is performed first. Why is the code inside FN not waiting for 1000 milliseconds to output 123 and then output 567?
is because the timer is asynchronous, JS parsing to the timer, the timer will be thrown to the timer trigger, when the delay of 1000 milliseconds
And then throw it into the current task queue to execute. During this delay, the code in the task queue is still executing, not saying
After your timer executes, I'm doing it! If I'm doing it when you're done, it's slow baby.
And the use of time do not rely too much on the timer set the timer time, the delay time in strict sense is always greater than T, as to how much, it is necessary to see the implementation of JS at that time.
Setimeout registers the function to throw the task to the timed trigger thread, and the timing trigger will add FN to the main process execution queue once the delay time is reached. However, if the current task queue still has code that is not finished executing, and you need to wait for the current task to finish executing
To FN, so the actual delay will be longer than the set time. If you set a big loop before FN, you wait. Ah haha haha
Clear the timer, if not clear the timer, will continue to the current task list to add task execution, will be the task list to chaos
Code Execution order time the error is big your page will be GG so run out to clear.
Timer =setinterval (fn,t);
Clearinterval (timer);
Similarly
Read it should be able to understand it to a praise after reading!!!
JScript timer, always use something, do you really understand?