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.
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
The JS setTimeout() method will call a function after the time specified in milliseconds (1000 ms = 1 second) has passed. The specified function will be executed once.
A new alternative is window. requestAnimationFrame() , which is less resource-intensive, disabled on page blur, and does not slow down other stuff. This makes it the perfect substitute for a modern setTimeout() and setInterval() .
Save this answer. Show activity on this post. clearTimeout is only necessary for cancelling a timeout. After the timeout fires, it can safely be left alone.
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.
This is now possible with Await/Async in a quick one line:
await new Promise(resolve => setTimeout(resolve, 1000));
There is another question I think is relevant at Combination of async function + await + setTimeout
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With