Search code examples
javascripttimeoutsettimeout

Js: setTimeOut without function argument?


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.


Solution

  • 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.