Possible Duplicate:
Delay to next function in method chain
There are 4 functions…
function fn1()
{
setTimeout(function()
{
$("#div_result_area").append('Calling from function 1<br/>');
},5000);
}
function fn2()
{
setTimeout(function()
{
$("#div_result_area").append('Calling from function 2<br/>');
},4000);
}
function fn3()
{
setTimeout(function()
{
$("#div_result_area").append('Calling from function 3<br/>');
},3000);
}
function fn4()
{
setTimeout(function()
{
$("#div_result_area").append('Calling from function 4<br/>');
},1000);
}
Now, when I am calling these in my button click event, one by one, it doesn’t work. The button click event –
$("#cmd_sync_tally").click(function(event){
event.preventDefault();
fn1();
fn2();
fn3();
fn4();
});
The result should have been like first function 1 executes & writes the value, then function 2 and so on.
Calling from function 4
Calling from function 3
Calling from function 2
Calling from function 1
I wonder, how to make these calls sequential, so that functions execute one after another.
All your functions are programmed at the same time, which is the start from the timeout count.
If you want to call functions programmed at the same time sequentially the cleanest solution is to chain them :
You can use the callback pattern for this :
You could also define your timeouts so that they add up :
But if you do this a lot, with more functions that you want to queue, then the best would be to implement a queue, as is done in jQuery. You can see such an implementation in this related question.