Talking about JavaScript running mechanism from settimeout

Source: Internet
Author: User
Tags sleep function


Recently I was looking at some JavaScript asynchronous things, but because of the limited time, just looked at the head, had to stop halfway. In order to facilitate the future inspection for re-pick up, then recorded a little experience, if it can make others gain, it is very good. In fact, this article is not much related to asynchrony.

From SetTimeout.

As we all know, JavaScript is a single-threaded programming, what is a single-threaded, that is, the same time JavaScript can only execute a piece of code, if the code to execute a long time, then the code can only enjoy waiting for it to execute, not like people, people are multi-threaded, So you can watch an island action movie while you sweat. The JavaScript single-threaded mechanism is also a necessity, assuming that there are multiple threads, while modifying a DOM element, then exactly which thread to listen to?

Now that JavaScript is a single-threaded language, it's understandable that we find ways to think of JavaScript's asynchronous approach. For example, execute to a piece of code, the requirement is 1000ms after call method A,javascript No sleep function can suspend thread for one second ah? How can you make the code wait for the A method to execute while continuing to execute the following code, as if two threads are open? The mechanics of the scientists came up with a settimeout method.

SetTimeout method Presumably everyone is already familiar with, then settimeout (function () {.}, a) is it true that AMS executes the corresponding callback?

SetTimeout (function() {  console.log (' Hello World ');  while (true) {};

After 1s, the console does not have the same output string as expected, and the circle on the tab of the page has been spinning and turning, pinching a count, and possibly falling into the dead loop of while (true) {}, but why? It's going to be a dead loop, but you have to output the string first! This is going to be a JavaScript run mechanism.

JavaScript operating mechanism

How exactly does a piece of JavaScript code work? Nanyi teacher has a good article (JavaScript running mechanism in detail: again on the event Loop), I will not repeat the wheel, if it is too long to see, the landlord briefly plain English description. A section of JS code (which may contain some settimeout, mouse clicks, Ajax and other events), from top to bottom to execute, encountered settimeout, mouse clicks and other events, asynchronous execution of them, at this time does not affect the code body continues to execute, once the asynchronous event is executed, Callback functions return, adding them sequentially to the execution queue, it is important to note that if the principal code is not finished, it will never trigger callback , which is why the above code causes the browser to suspend animation (while (true) {} in the main code) Not done yet).

There is also a wide-spread article on the internet (poke how JavaScript timers work), the article has a very good picture, I stole it.

There is no code for this diagram in the article, and in order to better illustrate the process, I try to give the code:

 //  some code  settimeout ( function   () {console.log ( ' Hello '  10 //  some code  document.getelementbyid ( ' btn '  "). Click ();  //  some code  setinterval ( function   () {Console.log ( ' World '  10 //  some code  

Let's start executing the code. The first piece of code probably executes 18ms, that is, the JavaScript body code, in the execution process, first triggered a settimeout function, the code continues to execute, only 10ms after the response settimeout callback, followed by a mouse click event, This event has a callback (perhaps something called alert), cannot be executed immediately (single thread), because the JS principal code is not finished, so this callback is inserted into the execution queue, waiting for execution; then the SetInterval function is executed, we know, Thereafter every 10ms will have a callback (try) into the queue, run to 10ms, the callback of the SetTimeout function is inserted into the queue. JS function after the main body run, about 18ms this point, we found that there is a click in the queue callback, there is a settimeout callback, so we first run the former, in the process of operation, SetInterval 10ms response time is too , the same callback is inserted into the queue. Click Callback Run finished, run SetTimeout callback, then 10ms passed, SetInterval again produced a callback, but this callback was abandoned, then what happened to everyone at a glance.

One thing I don't quite understand here is the drop of the interval callback. According to how the JavaScript timers work says that if the wait queue already has a callback for the same interval function, there will not be the same callback inserted into the wait queue.

"Note that while mouse click handler is executing the first interval callback executes. As with the timer it handler is queued for later execution. However, note that when the interval was fired again (when the timer was handler) this time that executing handler Is dropped. If you were to queue up all interval callbacks when a large block of code was executing the result would be a bunch of inte Rvals executing with no delay between them, upon completion. Instead browsers tend to simply wait until no more interval handlers is queued (for the interval in question) before Queu ing more. "

Find a predecessor's article JavaScript Timer learning note, which says "in order to ensure that the timer code is inserted into the queue the total minimum interval for the specified time." When using SetInterval (), the timer code can be added to the code queue only if no other code instance of the timer is available. But I practiced it myself and thought it might not be the case:

var startTime = +new  Date; var count = 0; var handle = SetInterval (function() {  console.log (' Hello World ');  Count++  ; if (count = =);  while (+New Date-starttime < 10 * 1000) {};

According to the above, the same setinterval callback cannot be added to the wait queue due to the "blocking" of the while to the thread, but the actual strings of 1000 Hello World are output in both chrome and FF consoles. I also go to the original blogger's article under the message asked under, for the moment still did not reply to me, may be my understanding of the setinterval of the posture of the wrong cause, if you know friends still hope to enlighten, extremely grateful!

In short, the timer simply adds code to the code queue at some point in the future, and execution timing is not guaranteed.

SetTimeout VS setinterval

Previously seen such words, setinterval function can be used settimeout to achieve, think also, the endless recursive call settimeout is setinterval it?

SetInterval (function() {  //  some code}, 10);

According to the previous description, we probably understand the execution time difference of the above setinterval callback function <=10ms, because the thread may be blocked, so that a series of callbacks are all queued. What is the setinterval effect achieved with settimeout?

 //  1    Func () {setTimeout ( function    () { //   Some code   Func (); },  10 //  setTimeout (function   () { //  some code  setTimeout ( Arguments.callee, 1000); 

It is clear that the interval between the two callbacks is >10ms, because the previous callback is queued in the queue, and if not, the following callback is not executed, and >10ms is because the code in the callback also executes the time. In other words, the setinterval callback is tied, and the previous callback (with no execution) does not affect the latter callback (insert queue), while the callback between settimeout is nested, and the latter callback is the callback of the previous callback (a bit of a tongue twister meaning)

    1. A detailed explanation of JavaScript running mechanism: Another talk about event Loop
    2. In-depth understanding of javascript timing mechanisms
    3. How JavaScript Timers work

Talking about JavaScript running mechanism from settimeout

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.