I am communicating with a servlet that changes and saves an external file. Since this takes some time, I need some of my javascript functioncalls to happen sequentially so that the actions of one function don't interfear the actions of another function.
To do this, I wrote a 'sequential' function that takes another function that can only be called when the busyflag is set to false (i.e. when no other functioncall is handled at the same time). This is my code:
var busy = false;
function sequential(action) {
while(busy)
setTimeout(function(){sequential(action);}, 10);
busy = true;
action();
setTimeout(function(){busy = false;}, 100);
}
function test1() {sequential(function() {alert("test1");});}
function test2() {sequential(function() {alert("test2");});}
And this is the example on jsFiddle. For some reason this code this code keeps looping on the second call (when a functioncall has to wait).
I first implemented a solution like suggested by James Montagne, but after some searchin I found out that you can use the onreadystatechange property of the XMLHttprequest to set the busy-flag to true.
This code works like expected:
function sequential(action) {
if (busy) setTimeout(function(){sequential(action);}, 20);
else action();
}
function send(message){
busy = true;
var request = new XMLHttpRequest();
request.open("POST", "owlapi", true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send(message);
request.onreadystatechange = function() {busy = false;};
}