+ 1

Why is this loop stopping at 9 instead of 10.

Why is this loop stopping at 9 instead of 10 <!--HTML--> <p id = "name"></p> //Javascript window.onload = function () { function runLoop() { var iteration = 10; var name = document.querySelector("#name"); name.innerHTML = ""; var i = 0; var loopFunc = setInterval(function () { name.innerHTML += i + "<br>"; i++; if (i == iteration) { clearInterval(loopFunc); } }, 0.1); } runLoop(); } can someone explain why the output is 9 instead of 10 https://code.sololearn.com/W15mGo7gZ461/?ref=app

18th Jan 2021, 7:11 AM
Ibrahim Yusuf
Ibrahim Yusuf - avatar
5 Respuestas
+ 1
Try to imagination pre last statement when i==9. It comes to fuction, append text to inner html with 9+ br. Then icrease itself and now i becomes 10. Then you check if i equal 10 stop iterations. So last appending will not be done. Moreover in this code there are no checking on initial value. For example if you want to print only first value. So just exchange i++ and condition check and everything will be ok.
18th Jan 2021, 9:48 AM
george
george - avatar
+ 1
do i++ last
18th Jan 2021, 7:18 AM
durian
durian - avatar
+ 1
Mirielle I understand you well. But there is variable "iteration" in which 10 is assigned to it. And there is a conditional statement for when the variable "i" reaches the variable "iteration". Why doean't the last one count? I mean logic behind that.
18th Jan 2021, 8:01 AM
Ibrahim Yusuf
Ibrahim Yusuf - avatar
+ 1
george thanks man, your explanation really helps.
19th Jan 2021, 2:34 AM
Ibrahim Yusuf
Ibrahim Yusuf - avatar