2

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();

http://jsfiddle.net/z71gkpfg/

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

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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?

1 Comment

Above answer is simpler

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.