JavaScript you don't know: funny settimeout.

Source: Internet
Author: User

JavaScript you don't know: funny settimeout.

Sometimes small details tend to hide great wisdom.
Today, when looking back at JavaScript advanced usage, find an interesting question, say not much, first on the code:

 for(varj=0;j<Ten; j + +) {
SetTimeout ( function(){Console. log (j)}, the)
}

Seeing these three lines of code, you might be impatient: Talk about closures again? You're going to puke, okay? Don't worry, let's start by thinking, what is the result of this code executing in the browser?

A: Sequential printing 0 to 9?

B: I have seen this question, print 10 10!

Which answer is correct? We continue to:

Execution results show that the browser print 10 10 (because of the picture processing reasons, press the return to print before the fact that the interval of about 5 seconds), it seems that B won. But if you are careful enough, you will find a few questions:

    1. Why would I cycle 10 10 instead of 0 to 9?
    2. From the result, the For loop does not start executing settimeout (so j is equal to 10) after the bounce is performed, why is it not executed once per iteration settimeout?

If you can answer the above three questions, congratulations, you have begun to grasp the deep knowledge of JavaScript, if not, then look down!

Why does it cycle 10 x

Many people are accustomed to answering the question with the result of the second question: "After the For loop executes the jump, it starts executing settimeout, so it prints 10 10". Such an answer can only be said to deal with themselves, but also to deal with others. In fact, to answer the first question, the first one to answer is the second question.

Why is not every iteration executed once settimeout

As we all know, JavaScript before the advent of ES6, there is no block scope, which means that in the For loop variable J defined by Var, actually belong to the global, that is, in the global scope can be accessed, so, that is, in fact, the entire global scope is only one J, Each for loop i is updating this J.

So the key question now is why the entire for loop executes before settimeout, not what we normally understand, one iteration at a time.

This involves the core features of javascript: Single thread.

JavaScript is designed to be used by browsers to interact with the user and to manipulate the DOM. This determines that it must be single-threaded, imagine that a JavaScript colleague has two threads, one thread adds content to the DOM node, and a thread deletes that node, and the browser becomes cluttered. So, to avoid complexity, JavaScript is a single thread from birth, which has become a core feature of the language and will not change in the future.

A single thread means that all tasks need to be queued, and the previous task is completed before the latter one is executed. If the previous task takes a long time, the latter task has to wait.

To optimize single-threaded performance, JavaScript divides the task into two types, one synchronization task (synchronous) and one asynchronous task (asynchronous). A synchronization task is a task that is queued on the main thread to perform the latter task only if the previous task is completed, and the asynchronous task refers to a task that goes into the task queue without entering the main thread, and only the synchronization task in the main thread executes. The asynchronous task will not go into execution queue execution. As long as the main line Cheng, will read "task queue", this is the operation mechanism of JavaScript. This process is repeated.

SetTimeout, however, is defined by JavaScript as an asynchronous task. Each iteration of the for loop joins the callback function in the settimeout to the task queue for execution. That is, only the For loop in the synchronization task is completely finished, and the main thread will go to the task queue to find the 10 settimeout (10 iterations) callback functions that have not yet been executed and execute sequentially (FIFO). At this point, I has gone through the end of the loop into 10, so, at this time the main thread executes, is 10 a touch of the same print I callback function, that is, print 10 10. This is the perfect answer to the first and second questions, the article at the beginning of the code and the following code is actually equivalent:

 for(varI=0;i<Ten; i++) {}
SetTimeout (Console. log (i), the)
SetTimeout (Console. log (i), the)
SetTimeout (Console. log (i), the)
SetTimeout (Console. log (i), the)
SetTimeout (Console. log (i), the)
SetTimeout (Console. log (i), the)
SetTimeout (Console. log (i), the)
SetTimeout (Console. log (i), the)
SetTimeout (Console. log (i), the)
SetTimeout (Console. log (i), the)

A small settimeout, involving a lot of javascript deep-seated problems, although summed up into an article only a mere hundreds of words, but I in the process of writing a lot of information, but also done a lot of experiments.

Finally, give a small but still troubled me of a problem, I hope that interested partners can study with me:

SetTimeout ( function(){ while(true){}},6000);
SetTimeout ( function(){Console. log (1)},10000);
SetTimeout ( function(){Console. log (2)}, the);

What is the order of execution of the above code? Is the timing of the settimeout timed to execute immediately after the execution stack is inserted, or is it immediately inserted into the execution stack timing execution?

We look forward to your message.

JavaScript you don't know: funny 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: info-contact@alibabacloud.com 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.