6

I have a fiddle here

Can someone help me understand why the first setTimeout works but not on second one? Please see comments on the code.

In this case, I want to alert first I am first then after 6 seconds, it would alert Hello, sorry I am late

function iAmTakingTooLong(message1, message2, callback){       
    //setTimeout(function(){ alert('test'); },6000); //THIS WILL WAIT FOR 6000 MILLISECONDS
    setTimeout(callback(message1+message2),6000);    //THIS WILL NOT WAIT FOR 6000 MILLISECONDS
}


iAmTakingTooLong('Hello, ', 'sorry I am late!', function(fullmessage){
    alert(fullmessage);
});

alert("I am first!");

1 Answer 1

11

In this code:

setTimeout(callback(message1+message2),6000);

you're calling the callback function right there in the argument list. JavaScript evaluates function arguments before calling the function, so what actually gets passed to setTimeout() here is whatever the callback function returns.

You need something like:

setTimeout(function() { callback(message1 + message2); }, 6000);

The behavior here is not unique to JavaScript.

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

3 Comments

Thanks man, I am just wondering since I was thinking that the callback is already a function and doesn't need to put it inside function(){}
What would you expect callback(message1 + message2) to do outside of a call to setTimeout()?
I am expecting that without putting callback(message1+message2) inside function(){}, it would call the callback only after the specified time. But it seems that is not the case. Thank you.

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.