admin管理员组

文章数量:1202351

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 is firing 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 300000 instead, same problem.

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 is firing 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 300000 instead, same problem.

Share Improve this question asked Jun 8, 2012 at 14:13 SomeKittensSomeKittens 39.5k19 gold badges115 silver badges145 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 20

You are calling tweet immediately and passing its return value to 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 return a function.

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

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

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.

本文标签: javascriptUsing setTimeout() for large valuesStack Overflow