设置超时不使用功能 [英] set time out not working with function

查看:58
本文介绍了设置超时不使用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下内容暂停javascript几秒钟:

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?

推荐答案

您需要传递函数引用。你正在传递函数的返回值。

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

区别在于:一个是你想要发生的函数的蓝图,另一个是你立即执行函数的蓝图。将其返回值传递给 setTimeout

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

这篇关于设置超时不使用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆