Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Js: setTimeOut without function argument? [duplicate]

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.

like image 218
giorgio79 Avatar asked Feb 09 '15 09:02

giorgio79


People also ask

Does setTimeout repeat?

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.

How many times does setTimeout () execute the function parameter?

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.

What is the alternative for setTimeout in JavaScript?

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() .

Is clearTimeout necessary?

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.


2 Answers

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.

like image 55
KooiInc Avatar answered Sep 20 '22 16:09

KooiInc


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

like image 24
Mario Figueiredo Avatar answered Sep 24 '22 16:09

Mario Figueiredo