最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Callback timeout - Stack Overflow

programmeradmin3浏览0评论

I have a fiddle here

Can someone help me understand why the first setTimeout works but not on second one? Please see ments 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!");

I have a fiddle here

Can someone help me understand why the first setTimeout works but not on second one? Please see ments 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!");
Share Improve this question asked Mar 27, 2014 at 14:34 JunMJunM 7,1608 gold badges39 silver badges60 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论