I have a multi-users chat web pages written in JS and socket.io.
Many users can send messages simultaneously, when I receive a message, I need to run a function that changes the innerHTML of a DIV.
However, suppose there are 1000 messages send to be simultaneously, I want to run THAT function in sequence, one time after another.
i.e. DO NOT run another call for that function UNTIL last call is completed. (And the GLOBAL variables inside that function will NOT be changed by another call of the SAME function, until the current call is completed)
e.g. (I write the following example by using timer instead of socket.io event since it is much simple to understand)
Below is the Javascript:
var gInteger = 0;
var gbolChanging = false;
function changeInteger (intChange) {
if (!gbolChanging) {
gbolChanging = true;
gInteger += intChange;
divInteger.innerHTML = gInteger;
gbolChanging = false;
}
}
var timer1 = setInterval(changeInteger, 1, 1);
var timer2 = setInterval(changeInteger, 1, -1);
<div id="divInteger">
</div>
Above is the HTML:
The expected result of the above html and js is:
You should see only 0 or 1
The actual result is:
You may see -1 and 2 as well if you run the program long enough. (i.e. both timers detects bolChanging = false at the same time)