Let's say I have a button with an event handler:
<button onclick="btnClicked()"> CLICK ME </button>
and this is the js file:
var num = 0; // global variable
function btnClicked() {
num++;
console.log(num);
}
Let's say that I clicked twice on the same button. I expect to see in console 1 and then 2.
But, it's not necessary that this is what I will get. Each button click invokes the function btnClicked
asynchronously, so there is a possible scenario that the second call will end before the first call ends. e.g. The first invocation calls btnClicked
, passes the line num++
and then holds (for some reason). Meanwhile, second invocation enters the function that num = 1, increments it to 2, prints 2 in console, and then the first invocation continues its execution with num=2 and therefore also prints 2.
Do you know any way to make sure that second invocation will occur only after first invocation ends ?