MLister
MLister

Reputation: 10300

Conditionally delay function execution

In front-end JavaScript, I have a function funcA which normally executes as soon as the client receives a particular message A.

It is possible that the server will send another message B before sending A. When this happens, the client will receive two messages: first B then A, and a different function funcB (triggered by B) will execute before funcA.

Now, is there an elegant way to delay the execution of funcA upon receiving A, if funcB executes first?

Some pseudo-code below to illustrate the idea:

...

// called upon receiving msg `A`
// but need to delay its execution if receiving `B` and executing funcB first
function funcA(param) {
    ...
}

// called upon receiving msg `B`
function funcB(param) {
    ...
}

...

// receiving messages from server

var msg = JSON.parse(...);

if (msg.type === 'A') {
    funcA(msg.data);
}
else if (msg.type === 'B') {
    funcB(msg.data);
}
else if (msg.type === 'C') {
    ...
}

// deal with other types of message
...

I can think of using the combination of a 'flag' and conditional check before every execution of funcA, which doesn't seem very elegant to me.

Please note: this question is not about how to delay the execution of a function (which is usually achieved by using setTimeout), instead, it asks for a design pattern/structure given a particular code logic.

Upvotes: 0

Views: 646

Answers (1)

Guffa
Guffa

Reputation: 700362

You need a way to keep track if funcB has been called, then you can check for that inside funcA and let it call itself with a delay:

var funcBCalled = false;

function funcB() {
  funcBCalled = true;
  // do something...
}

function funcA() {
  if (funcBCalled) {
    funcBCalled = false;
    window.setTimeout(funcA, 1000);
  } else {
    // do something
  }
}

Upvotes: 2

Related Questions