First, the event cycle
JavaScript is single-threaded and can only do one thing at a time, so the task needs to be queued. If the previous one takes a long time, then the next can only wait.
1) Two Kinds of tasks
To better handle tasks, the designer of the JavaScript language divides the tasks into two types: synchronous tasks (synchronous) and asynchronous tasks (asynchronous).
Synchronization Task : A task that is queued for execution on the main thread.
Asynchronous Tasks : Placed in the task queue, the tasks in the task queue are placed in the main thread only if the mainline Cheng.
This is how JavaScript works, and this process repeats itself, called the event loop .
2) Event loop
The event loop model can be described in the picture from Philip Roberts's speech, "Help, I ' m stuck in an event loop":
1. The "Webapis" is an asynchronous task, including Dom events, Ajax, and SetTimeout.
2. Within the "callback queue" is a queue of tasks, including click, Load, done.
3. In the "stack" is the synchronization task, only when the "stack" is emptied, will not be polled task queue.
Here is a description of the code, the content of the picture is the result of printing, no suspense.
Console.log (' Hi '); SetTimeout (function() { console.log (' there ');},5000 ); Console.log (' SJS ');
1. Put the log (' Hi ') method into the stack, this is a common method, the stack is executed by the engine, output "Hi".
2. Put the settimeout method into the stack, this is a method within the Webapis, the stack is passed to the corresponding module by the engine, continue to process the following code.
3. Add log (' SJS ') to the execution stack and output "SJS" from the stack.
4. After the SetTimeout method executes for 5 seconds, the trigger condition is reached and the settimeout is added to the task queue.
5. The execution stack at this time is empty, so the engine starts polling the check task queue, there is a settimeout, so the settimeout is added to the execution stack.
6. In settimeout, there is a log (' there ') method, this method is put into the stack, output "there".
3) loop process to take Ajax
Shows the main thread to get AJAX messages through the event loop process:
Second, the timer
Timers are setTimeout (FN, delay) and setinterval (FN, delay), which are not guaranteed by the timer set delay.
If SetTimeout is called at point-in-time "n" , then the JavaScript task that executes the timer code is added to the message queue after "N+delay" .
is an example diagram of the author of jquery, John Resig, drawing:
The left is the run time (in ms), the middle is the JavaScript snippet, and the right is the time the code is scheduled to start executing .
1.0ms JavaScript begins execution, 2ms start settimeout,6ms join mouse click,10ms start setinterval,12ms join settimeout,20ms Add setinterval,30ms , 40ms, 50ms join SetInterval.
2. The 1th paragraph of JavaScript executes approximately 18ms, at 18ms, when the settimeout expires.
3. Follow the single-threaded FIFO rule, then execute mouse click, then run SetTimeout and setinterval in turn.
4.1th setinterval (20ms added) is still waiting in line, 30MS will join SetInterval, but the browser only let one setinterval queue, the others are discarded.
5. The 1th setinterval starts at 36ms, this program needs to execute 6MS, 2nd setinterval starts to queue at 40ms, and starts execution at 42ms.
6. The 2nd executed setinterval is executed at 48ms, and 3rd setinterval begins execution at 50ms, and does not need to be queued and run directly.
Three, the Division task
When JavaScript executes, all the update operations for page rendering are paused. When performing a busy time, it may cause the browser to get stuck or seem to hang up.
Timer, you can effectively pause the execution of a piece of JavaScript code, and you can break down parts of the code into fragments that won't let the browser hang up.
1) Code not optimized
Long-running tasks , using mobile phone scanning QR code to see the effect will be more obvious
var tbody = document.getElementsByTagName ("tbody") [0"; for (var i = 0; i < 20000; i++) {// Create 20,000 tr var tr = document.createelement ("tr" for (var t = 0; t < 6; t++) {// Each TR has 6 TD var td = Document.createelement ("TD" + "," + T)); Tr.appendchild (TD); } tbody.appendchild (TR); // add tr to tbody }
2) Optimized code
Use the timer Decomposition task to convert a strong loop into a non-blocking operation:
//configuration SectionvarRowCount = 20000; varDivideinto = 4; varChunkSize = Rowcount/divideinto;//divide 20000 into 4 partsvarIteration = 0; varTable = document.getElementsByTagName ("tbody") [0];settimeout (functiongeneraterows () {varBase = chunkSize * iteration;//calculate where the last outage was //Add TR Section for(vari = 0; i < chunkSize; i++) { varTR = document.createelement ("tr"); for(vart = 0; T < 6; t++) { varTD = Document.createelement ("TD"); Td.appendchild (document.createTextNode (i+ Base) + "," + t + "," +iteration)); Tr.appendchild (TD); } table.appendchild (TR); } Iteration++;//scheduling the next stage if(Iteration <divideinto) setTimeout (Generaterows,0); }, 0);
Resources:
How the JavaScript timer works
JavaScript: A thorough understanding of synchronous, asynchronous, and event loops (events loop)
From SetTimeout, the event cycle model
A detailed explanation of JavaScript running mechanism: Another talk about event Loop
JavaScript Ninja Cheats
Opinion: Talk about how JavaScript timers work
JavaScript Timer analysis