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.