Home » Javascript » JavaScript message queue execution timing

JavaScript message queue execution timing

Posted by: admin November 1, 2017 Leave a comment

Questions:

As a disclaimer, I’m out of my depth here, my friend is the one who’s actually facing this problem and I’m curious about what’s going on.

I come from a more javascript/node.js background, so as I understand it

let a = 10
setTimeout(() => (a = 20))
a = 0;

a = 20 will always execute last, in other words, after a = 0

My friend has a piece of code which is similar, but was written for android

// handler is created somewhere in this same thread
a = 10;
handler.sendMessage(20);
a = 0;

He claims, the handler’s handleMessage method has a reference to a, and will set a to 20 when the queue is ready.

The problem is after sometime, in a different thread, when he checks a’s value, most of the time it’s 20 but very rarely it’s 0. He’s also very sure that handleMessage has been executed already by that point. How does this happen?

Is handleMessage not guaranteed to be ran last like my example in javascript? If not how do I solve this gracefully?

Sorry for my awful pseudo codes but I’m really curious about this, would really appreciate it if somebody can point me in the right direction.

Answers: