I want widget.Rotator.rotate()
to be delayed 5 seconds between calls... how do I do this in jQuery... it seems like jQuery's delay()
wouldn't work for this...
Asked
Active
Viewed 5e+01k times
261

Ben
- 60,438
- 111
- 314
- 488
-
4Do you want it to automatically be called with a delay of 5 seconds between invocations, or will this be called in response to a user action and you want to ensure that it waits at least 5 seconds after the last invocation before going again? If the latter, should the user be able to queue up events, or should the input be ignored if 5 seconds have not elapsed? – Phrogz Jan 19 '11 at 17:38
-
4I understand that this is a duplicate, but 5 times more people land on this question because of the way the title is composed. Many of us are searching for the keyword _delay_ and not _sleep_. And the answer is more general too. So, in this case, this question is more relevant than the other, in my opinion. – Barnee Oct 10 '18 at 09:19
2 Answers
581
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
-
57If there are no function parameters, there is no need to wrap in a `function` - this will do fine: `setTimeout(your_func, 5000);` – Oded Jan 19 '11 at 17:36
-
1@Oded Are you sure that `Rotator.rotate()` does not need the receiver to be set to `Rotator`? If you perfom what you suggest, `this` will be the window. – Phrogz Jan 19 '11 at 17:39
-
1
-
3I suggest you modify your answer to say _"If your function has no parameters and no explicit receiver"_, or something similar but worded in a manner more clear to new programmers. – Phrogz Jan 19 '11 at 17:45
-
3Also, you can use clearTimeout(myTimer) to stop the function from being called, if you use myTimer=setTimeout(...) when first calling setTimeout. – Vern Jensen Aug 07 '13 at 22:36
-
33
var rotator = function(){
widget.Rotator.rotate();
setTimeout(rotator,5000);
};
rotator();
Or:
setInterval(
function(){ widget.Rotator.rotate() },
5000
);
Or:
setInterval(
widget.Rotator.rotate.bind(widget.Rotator),
5000
);

Phrogz
- 296,393
- 112
- 651
- 745