SoluableNonagon
SoluableNonagon

Reputation: 11755

Conditionally wrap code in a timeout using javascript

I have a few lines of code which I want to possibly wrap in a timeout based on a flag. The simple way to do this is:

var myCondition = // true or false
if(myCondition){
     setTimeout(function(){
         myVar++;
         myFunction();
         something = somethingElse;
     }, 1000 );
} else {
    myVar++;
    myFunction();
    something = somethingElse;
}

Is there a shorter way to achieve this? like using .call in some fashion?

As pointed out in the comments, I know I can just wrap the code in a function:

var myWrapperFunction = function(){
    myVar++;
    myFunction();
    something = somethingElse;
}

But what I'm looking for is a conditional way to just apply timeout in a manner shorter than above.

Upvotes: 0

Views: 1490

Answers (1)

epascarello
epascarello

Reputation: 207527

Not sure why shorter makes it better or easier to understand. Simpliest way to make it shorter it to put the common code into a function and assign it or call it based on the conditional.

var fnc = function () { /* common code */};
if (x) { 
    setTimeout(fnc, 1000); 
} else {
    fnc(); 
}

or set the timeout to zero

var time = x ? 1000 : 0;
setTimeout(fnc, time);

Upvotes: 1

Related Questions