Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  39] [ 4]  / answers: 1 / hits: 59641  / 8 Years ago, thu, june 9, 2016, 12:00:00

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?


More From » while-loop

 Answers
137

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>







Although setInterval() can be used here





var myFunc01 = function() {
var i = 0;
// store the interval id to clear in future
var intr = setInterval(function() {
document.getElementById('d01').innerHTML += 100 - i + <br>;
// clear the interval if `i` reached 100
if (++i == 100) clearInterval(intr);
}, 1000)

}

myFunc01();

<span id=d01></span>




[#61831] Wednesday, June 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
davion

Total Points: 458
Total Questions: 109
Total Answers: 100

Location: Taiwan
Member since Mon, Sep 6, 2021
3 Years ago
;