I'm trying to add a delay in one of my loops but I get unexpected results. I've looked at many similar questions but since I'm trying to learn javascript I want to know why this isn't working and how I can get it to work.
If you look at the script below, shouldn't it go like this:
- cars[1]
- sleep(); (wait 3 sec then return)
- add 1
- Run the script again
- cars[2]
- etc ...
With output:
- Saab
- Waiting 3 seconds...
- Volvo
- Waiting 3 seconds...
- etc ...
But the output I receive is:
- Saab
- Volvo
- BMW
- Done
(Waiting 3 seconds here)
- Waiting 3 seconds...
- Waiting 3 seconds...
- Waiting 3 seconds...
Am I stupid or is javascript working entirely different than C++ and assembly?
var nr = 0;
const qty = 3;
function script() {
main();
console.log("Done");
}
function main() {
var cars = ["Saab", "Volvo", "BMW"];
if (nr !== qty) {
console.log(cars[nr]);
sleep();
nr++;
main();
}
else {
return;
}
}
function sleep() {
setTimeout(function () {
console.log('Waiting 3 seconds...');
return;
}, 3000);
}
<!DOCTYPE html>
<HTML>
<HEAD>
</HEAD>
<BODY>
<button onclick="script()">Run Script</button>
</BODY>
</HTML>
setTimeoutdoesn't block the script execution.setTImeout(function()will executed after 2000mssetTimeoutfromsleep, like everyone saidfunction recursiveFn() { doStuff(); setTimeout(recursiveFn,3000) }BTW, yoursleep()fn says "waiting 3 seconds" but it's only set to for 2000ms or 2s.