javascript 对大值使用 setTimeout()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10950533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:35:49  来源:igfitidea点击:

Using setTimeout() for large values

javascript

提问by SomeKittens

I'm trying to get an event to fire after five minutes. I'm using the following code:

我试图在五分钟后触发一个事件。我正在使用以下代码:

setTimeout(tweet(name, type), 5 * 60 * 1000);

It isfiring after a while, but not nearly five minutes (Usually two minutes or so, but sometimes it's instant.). What am I doing wrong? (I've also tried setting the time to 300000instead, same problem.

一段时间后射击,但不是将近五分钟(通常是两分钟左右,但有时它的即时)。我究竟做错了什么?(我也试过将时间设置为300000同样的问题。

回答by Quentin

You are calling tweetimmediately and passing its return value to setTimeout.

您正在tweet立即调用并将其返回值传递给setTimeout.

You need to pass a function to setTimeout. You haven't included the code for tweet, but I'm going to assume that it doesn't returna function.

您需要将函数传递给setTimeout. 您尚未包含 的代码tweet,但我假设它不是return函数。

setTimeout(function () { tweet(name, type); }, 5 * 60 * 1000);

回答by Florian Margaine

Quentin's solution works, but you can also use this form:

Quentin 的解决方案有效,但您也可以使用以下形式:

setTimeout(tweet(name, type), 5 * 60 * 1000);

function tweet(name, type) {
    return function(name, type) {
    };
}

It has some use cases when you want to keep some values in a closure.

当您想在闭包中保留某些值时,它有一些用例。