JS Classic Interview Question: How do I make the settimeout () function in the For loop work as expected?

Source: Internet
Author: User

It is possible that people often encounter situations like the following:

 for (var i = 1; I <= 2; i++) {    setTimeout (function() {alert (i)}, +);}

After running, the alert two times the content is the number 3, instead of what you expected first 1 after 2. There is a basic interview question, how to make reasonable changes to the code so that it returns the desired results?

It's actually very simple. In the StackOverflow of the Great God explained, you can refer to this link

The answers are translated into Chinese as follows (and some modifications are made to facilitate understanding):

---------------------------------------------------------------------------------

you want < Span id= "Ouhighlight__26_33to5_6" > each timer processing function Create different "i" Variable copy

function Dosettimeout (i) {  setTimeout (function() {alert (i);}, +);}  for (var i = 1; I <= 2; + +i)  dosettimeout (i);
IfYouNoDoSuchOfThings(This approach will in factYesOther variants),EachTimerProcessingfunction willShared in the same scopeSameVariable"I".WhenCycleCompleteWhenWhat's the "I"??Is3! Over hereBy definingA function to implementMediationOfRole, which createsTheVariableOfValueOfCopy。since settimeout () is called in the context of the replica , it has its own private "I" each time for use .

But over time, the effect of these codes is somewhat confusing, as the fact that setting up some contiguous settimeout () with the same time interval will cause all delay handlers to be called at the same time. It is important to understand that setting a timer (call to SetTimeout ()) is hardly time consuming. That is, telling the system "call this function after 1000 milliseconds" will be returned immediately, because the process of installing the delay request in the timer queue is very fast.

So, if there is a series of continuous delay requests (like the code in my answer), and each time delay value is the same, thenonce enough time has elapsed , all the delay handlers will be called one after another quickly and consecutively .

span> If you need a handler that is called at regular intervals, you can use SetInterval (), which behaves very much like settimeout (), but runs once every time. Or you can call " time value multiplied iteration Counter" is the settimeout of the time interval . In other words, modify the sample code I just had:
function Doscaledtimeout (i) {  setTimeout(function() {    alert (i);   *);}

(100 milliseconds timeout, the effect will not be obvious, so I set the number up to 5000)

The "I" value is multiplied by the underlying delay value, so looping 5 times will result in a delay of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds respectively.

JS Classic Interview Question: How do I make the settimeout () function in the For loop work as expected?

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.