Currently, I am working on creating a stopwatch in JavaScript that counts by milliseconds using setTimeout. However, I encountered an issue during the initial setup:
var time = 0;
function main() {
for (var i = 0; i < 5; i++) {
setTimeout(timer, 1);
}
alert(time + " after the loop");
}
function timer() {
time++;
alert(time + " inside the loop");
}
document.getElementById("go").onclick = main;
#go {
height: 40px;
border: 1px solid lime;
border-radius: 10px;
background-color: lime;
}
<button id="go">Start!</button>
It seems like this piece of code is skipping over the for loop to the alert and then going back to the for loop. Can anyone explain what's happening here? My past experience with Python tells me that if you call a function within another function, the called function gets executed before moving to the next line of code in the main function. Does JavaScript operate similarly? Excuse my messy code, as I am still learning HTML/CSS/JavaScript.