While the loop returns only the final result

while (counterInc < counter) {
  window.setTimeout(function () {
    $('#results').text(counterInc);
    }, 3000);
  counterInc++;
}

This code should increment the tag with the results ID every 3000 milliseconds, while the while loop is running and returns the final result. For example, instead of changing the text to 1, 2, 3, 4, 5, .. n, it changes the text to n. How would each loop update the text box every 1000 milliseconds with each increment, and not just with the final result?

+5
source share
4 answers

try it

var counterInc = 0;
var counterMax = 10;

var timeoutId = window.setInterval(function() {
    $('#results').text(counterInc++);
    if (counterInc >= counterMax) {
        window.clearInterval(timeoutId);
    }
}, 500);​

http://jsfiddle.net/GufCs/4/

What happened was that you timeout updated the cell every three seconds, however, your cycle can go through an absurd number of numbers in 3 seconds, so it has already been completed by the time the function runs in setTimeout.

500 ( 3000 ), . , counterMax.

+7

, setTimeout() " ". , . " " : .

+2

, , . , , .

, setTimout, , : http://jsfiddle.net/lechevalierd3on/jhYm3/

var counter = 10;
var counterInc= 0;

while (counterInc < counter) {
  window.setTimeout(function () {
      var inc = counterInc;
      return function(){
          $('#results').text(inc);
      }
  }(counterInc), 1000 * counterInc);   

  counterInc++;
}​
+1
while (counterInc < counter) {
  window.setTimeout(function () {
    $('#results').text(counterInc);
    }, 3000 * counterInc++);
}
-2

All Articles