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

javascript - set time out not working with function - Stack Overflow

programmeradmin4浏览0评论

I am using the following to pause the javascript for a few seconds:

 setTimeout(start_countdown(),3000);

It does not work, the function is called regardless of the seconds. The following function does however work, which doesnt use a function.

setTimeout(alert('hi'),3000);

How can I solve this?

I am using the following to pause the javascript for a few seconds:

 setTimeout(start_countdown(),3000);

It does not work, the function is called regardless of the seconds. The following function does however work, which doesnt use a function.

setTimeout(alert('hi'),3000);

How can I solve this?

Share Improve this question asked Aug 1, 2012 at 10:13 JakeJake 3,4867 gold badges41 silver badges60 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 11

You need to pass a function reference. You are passing a function's return value.

The difference is this: one is a blueprint of the function you want to happen, the other means you are executing the function immediately and passing its return value to setTimeout.

setTimeout(start_countdown, 3000);

If you want to do something more plex than simply call a named function, OR you want to pass a param to the named function, you'll need to instead pass an anonymous function to the timeout and call your function within that:

setTimeout(function() {
    start_countdown(/* possible params */);
    /* other code here as required */
}, 3000);

If you dont need to pass params dont use ()

setTimeout(start_countdown,3000);

If you do you have to wrap your function

setTimeout(function(){start_countdown(parameter)},3000);

write instead

setTimeout(start_countdown, 3000);

without parens ()
the second example could be also written as

setTimeout(function() { alert('hi'); }, 3000);

In different browsers it works in different way. In IE you need to use the anonymous function to pass the parameters to the callback:

setTimeout(function(){alert('hi')},3000);

发布评论

评论列表(0)

  1. 暂无评论