AngryHacker
AngryHacker

Reputation: 61646

Is there a better conditional setTimeout pattern?

I have the following code:

if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}

It seems like there should be a better pattern than calling flyOut in each if condition. Seems wasteful to me and pollutes the code.

Is there a better way?

Upvotes: 2

Views: 1132

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206618

Using if else

if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}

Using Conditional operator ?:

setTimeout(flyOut, isFlyoutAnimationDisabled ? 0 : 250);

by using the above consider that setTimeout(fn, 0) will perform as a "nextTick" giving this seemingly unexpected result

const fn = () => console.log("A");

setTimeout(fn, 0) // "A"
console.log("B"); // "B"

// Logs:
// >> B
// >> A

Upvotes: 2

themefield
themefield

Reputation: 4265

async function foo() {
  const delay = isFlyoutAnimationDisabled ? 0 : 250;
  await new Promise(x => setTimeout(x, delay));
  flyOut();
}

Literally no if-else needed. Promise is used here, and concurrency issue is avoided. Inspired by @Bergi's answer.

Upvotes: 1

Ricardo Spinoza
Ricardo Spinoza

Reputation: 199

Use the ternary operator, for example:

isFlyoutAnimationDisabled ? flyOut() : setTimeout(flyOut, 250);

Upvotes: 1

Bergi
Bergi

Reputation: 665455

If you can use promises, conditionals are simple:

function delay(t) {
    return new Promise(resolve => setTimeout(resolve, t));
}

async function example() {
    if (!isFlyoutAnimationDisabled)
        await delay(250);
    flyOut();
}
// or without async/await:
function example() {
    return (isFlyoutAnimationDisabled
      ? Promise.resolve()
      : delay(250)
    ).then(flyOut);
}

Upvotes: 2

Related Questions