Js: setTimeOut without function argument?

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