Can someone explain why this works (i.e. delay 1 executes before delay 2):
function testCallBack() {
one(two);
}
function one(callback) {
setTimeout(function () {
alert("delay 1");
callback();
}, 2000);
}
function two() {
setTimeout(function () {
alert("delay 2")
}, 1000);
}
testCallBack();
but this doesn't (delay 2 somehow executes before delay 1):
function testCallBack() {
one(two(three));
}
function one(callback) {
setTimeout(function () {
alert("delay 1");
callback();
}, 3000);
}
function two(callback) {
setTimeout(function () {
alert("delay 2");
callback();
}, 2000);
}
function three(){
setTimeout(function () {
alert("delay 3");
}, 1000);
}
testCallBack();
https://jsfiddle.net/511nLm95/
Am I not nesting my callback functions correctly?
2 Answers 2
You need to pass a function reference to one.
So here the solution could be is to pass an anonymous function as the callback to one which will call two with three as the callback reference.
function testCallBack() {
one(function(){
two(three);
});
}
Demo: Fiddle
Comments
This line is causing your troubles:
one(two(three));
Here you don't just pass the function name of two() as a callback, you actually execute the function and pass the returned value.
You could rewrite the statement like this without changing the semantics:
var resultOfTwo = two(three);
one(resultOfTwo);
Instead, actually just use two as a callback:
function testCallBack() {
one(two, three);
}
function one(callback, secondCallback) {
setTimeout(function () {
alert("delay 1");
callback(secondCallback);
}, 3000);
}
function two(secondCallback) {
setTimeout(function () {
alert("delay 2");
secondCallback();
}, 2000);
}
function three(){
setTimeout(function () {
alert("delay 3");
}, 1000);
}
testCallBack();
Do you understand why this solution works?