DWQA QuestionsCategory: ProgramA small question in front-end interview
zeng_js asked 2 months ago

Yesterday, I went to a company for an interview, and the second round of technical aspects gave me a question

var len=4;
while(len--){
    setTimeout(function(){
        alert(len);
    },0);
    alert(len);
}

When – outtime, – 0, – 0 is called, the output of – 1 is changed to 0

var len=4;
while(len--){
    (function(i){
        setTimeout(function(){
            alert(i);
        },0);
    })(len);
    alert(len);
}

This time, I know very well that a closure is generated. Every time the len changes I, a copy is saved, so the output is 3, 2, 1, 0, 3, 2, 1, 0. But when I wrote the demo just now, I found that the output of the first code met the expectation. The first four outputs of the second section were 3, 2, 1, 0. However, the output in the setTimeout is sometimes different, sometimes 0, 2, 1, 3 It’s 2, 1, 0, 3, etc.

52lidan replied 2 months ago

The first involves the knowledge of JS event loop. See:http://heroicyang.com/2012/08/28/javascript-event-loop/

52lidan replied 2 months ago

Isn’t this while loop an endless loop?

52lidan replied 2 months ago

This article is so good that it is praised by many people

5 Answers
Yiyun answered 2 months ago

Do you understand the one in front? Then I’ll just say the one at the back – closure.

 (function(i){ setTimeout(function(){ alert(i); },0); })(len);

Here you create a function and immediately call the parameters of the functioniIs set tolenAnd then it doesn’t change. So it’salertThe value of is 0-3 instead of – 1.
As for the sequence, the execution is delayed by 0 ms, so the order is out of order.

Youyu River replied 2 months ago

I see. The problem is on alert. use console.log There will be no such situation, because console.log It is synchronous. Alert involves suspending the browser process, which can be complicated

52lidan replied 2 months ago

Ha ha, the first paragraph is not output in sequence. The timer callback is executed at the end, but the len value remains unchanged, so they are all – 1. It happens that the second example proves this. The second example reveals the essence.

Youyu River replied 2 months ago

Attached: whatwg timer spec (see Clause 12)http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html

Super 2 God answered 2 months ago

In fact, the answer to the second question is truecertainYes:32103210
The reason why the last fouralert outputThere is uncertainty in the outcome of,andsetTimeoutAnd the delay timeIt doesn’t matter.The reason is that alert will block the execution thread of the browser, and all ways of blocking the execution thread will make the result of setTimeout uncertain.
(even if the delay time of setTimeout is 0, the callback function is strictly pushed into the queue stack and is called in the order of FIFO.)
For example, open the debugging tool and set breakpoints. If the breakpoint of the delayed callback function takes effect, the setTimeout setinterval and other results in the code will also be affected.
In this case, the best way is to use it as much as possible【 console.log 】Output the result, which only prints the object to the console without affecting the timeliness and order.

radical replied 2 months ago

Why does alert block the browser’s execution process

zhcexo answered 2 months ago

This problem is very strange. I put two pieces of code into the firebox console to execute. I used alert and replaced alert with alert console.log I’ve tried both of them. Both results are different from yours, and the results are also changing. I’m a little confused

52lidan answered 2 months ago

At first, I personally thought that timer callbacks were also queued in the event loop queue for processing. But the results given by the alert in chrome are not as good as I wish! Then I modified the theory partially for the time being.
After reading the reply of Yuxi children’s shoes, I was shocked. The goods are deceiving!
I don’t have to say much. I’ll give you a persuasive example and change the example given by the landlord.
To prove that timer callbacks are also queued and executed in sequence rather than delay time, I joined the
The code is as follows:

var test = function() {
    var len = 4;
    while (len--) {
        (function(len){
            setTimeout(function() {
                console.log('setTimeout log---' + len);
            }, new Date().getMilliseconds());
        })(len);
        console.log('log--'+len);
    }
};
test();
WARRIOR answered 2 months ago

Because the setTimeout is asynchronous, when the while loop ends and Len value is – 1, synchronization will hit 3, 2, 1, 0, and setTimeout will hit – 1, – 1, – 1, – 1
In the latter case, the closure principle is used. Each time the len value is the value entered during the loop, it will be passed into the setTimeout for caching, so output 3, 2, 1, 0, 3, 2, 1, 0