Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

javascript - setTimeout() method inside a while loop

I have read the relevant pages on w3schools and other similar questions here but cannot seem to understand what's wrong about the following bit :

var myfunc03 = function (i) {
  document.getElementById('d01').innerHTML += 100-i+"<br>";
};

var myFunc01 = function() {
  i=0;
  while (i<100) {
    setTimeout(myfunc03(i), 1000)
    i++;
  }
};

when myFunc01(); is run.

There's no pause whatsoever and all possible values for i is listed at once.

Is there a logical mistake here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The while loop will not wait for setTimeout() to complete. You need to set different time delay for each to execute them with different times and use closure for holding the value of i. Also in your case, function will be executed initially and return value is setting as argument in setTimeout(), so either you need to call the function inside an anonymous function or set the function directly.

var myFunc01 = function() {
  var i = 0;
  while (i < 100) {
    (function(i) {
      setTimeout(function() {
        document.getElementById('d01').innerHTML += 100 - i + "<br>";
      }, 1000 * i)
    })(i++)
  }
};

myFunc01();
<span id="d01"></span>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...