0

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.

4

1 回答 1

2

您需要一种方法来跟踪是否funcB已被调用,然后您可以检查内部funcA并让它延迟调用自身:

var funcBCalled = false;

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

function funcA() {
  if (funcBCalled) {
    funcBCalled = false;
    window.setTimeout(funcA, 1000);
  } else {
    // do something
  }
}
于 2013-08-13T11:40:04.140 回答