Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  93] [ 4]  / answers: 1 / hits: 43024  / 9 Years ago, mon, february 9, 2015, 12:00:00

Why do we need to pass a function to Javascript setTimeOut https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout



Why cannot we do sg simple like



setTimeOut(1000);


Can I pass an empty or nonexistant function in there?



I want to simply wait in a for loop after each iteration.


More From » timeout

 Answers
4

Javascript is single threaded. You can use setTimemout to postpone an operation, but the thread will continue. So



function some() {
doStuff();
setTimeout(otherStuff, 1000);
doMoreStuff();
}


will run doStuff and doMoreStuff subsequently, and will run otherStuff after a second. That's why it's useless and impossible to use setTimeout as a delay per se. If doMoreStuff should be postponed, you should make that the callback for the delay:



function some() {
doStuff();
setTimeout(doMoreStuff, 1000);
}


or both otherstuff and doMoreStuff delayed:



function some() {
doStuff();
setTimeout(function () {
otherStuff();
doMoreStuff()
}, 1000);
}


Maybe my answer to this SO-question is usefull too.


[#67897] Friday, February 6, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elvisissacg

Total Points: 410
Total Questions: 108
Total Answers: 121

Location: Monaco
Member since Tue, Jun 16, 2020
4 Years ago
;