How do I delay a function call for 5 seconds?

Go To StackoverFlow.com

159

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...

2011-01-19 17:33
by Webnet
Do 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 2011-01-19 17:38
I 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 - Barna Tekse 2018-10-10 09:19


335

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.

2011-01-19 17:35
by BrunoLM
If there are no function parameters, there is no need to wrap in a function - this will do fine: setTimeout(your_func, 5000);Oded 2011-01-19 17:36
@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 2011-01-19 17:39
@Phrogz - I was talking about the mechanics of setTimout - Oded 2011-01-19 17:41
I 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 2011-01-19 17:45
Also, you can use clearTimeout(myTimer) to stop the function from being called, if you use myTimer=setTimeout(...) when first calling setTimeout - Vern Jensen 2013-08-07 22:36


20

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
);
2011-01-19 17:35
by Phrogz
Ads