0

As far as a I know, there is no way to get setTimeout to run synchronously.

I have this code, where foo is a decently long function (20 lines or so).

if(delay == null){
  function foo(){

  }()
}
else {
   setTimeout(function(){
     function foo(){

     }()
   }, delay);
 }

what would very convenient, would be if setTimeout would accept an delay argument of -1, and then would just run synchronously/immediately, something like this:

var delay = delay || -1;

   setTimeout(function(){
     function foo(){

     }()
   }, delay);  // if delay is -1, will run immediately.

I don't think this functionality works with setTimeout, is there another way I can prevent having to write out the foo function twice? The only good solution I have is to create a helper function, but that's not as convenient :)

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

4 Answers4

3

Try this:

function foo(){

}
if(delay == null){
  foo();
}
else {
   setTimeout(foo, delay);
 }
JCOC611
  • 19,111
  • 14
  • 69
  • 90
1

Is there another way I can prevent having to write out the foo function twice?

Yep.

Define foo:

function foo() {

}

And then run it immediately if delay === -1, otherwise in a setTimeout:

if (delay === -1)
    foo();
else
    setTimeout(foo, delay);
Hatchet
  • 5,320
  • 1
  • 30
  • 42
0

This is really old, but you can simply just use an inline condition for the time delay.

setTimeout(foo, isDelay ? delay : 0)
mlangwell
  • 335
  • 1
  • 3
  • 12
  • `setTimeout(foo, 0);` might have an undesired effect. https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful – krzasteka Mar 30 '22 at 20:40
0

Mention "delay" time at least 1000 milisec.


setTimeout(foo, isDelay ? delay : 1000)