So I need a little delay in my JavaScript for a function inside a loop that should get called every 500 ms:
function myFunc(num) {
return num++;
}
var theNum = 0;
while (theNum != 10) {
theNum = setTimeout(myFunc(theNum), 500);
}
console.log("All done");
However, All done never gets logged.
You're calling the function immediately. You need to pass the function reference to the setTimeout instead.
And you're also creating an infinite loop due to that issue.
Even if you corrected this problem "All done" would still be logged first before any of the timeouts completed.
So you need to rethink the approach. Put the timeout in a function and if theNum is less that 10 call the function again with the incremented number (setTimeout allows you to pass in arguments after the delay). Log "All done" when the count reaches 10.
function myFunc(num) {
return `Number: ${num}`;
}
function loop(theNum = 0) {
if (theNum < 10) {
console.log(myFunc(theNum));
setTimeout(loop, 500, ++theNum);
} else {
console.log("All done");
}
}
loop();