How do I delay a function call for 5 seconds?

JavascriptJquery

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenView Question on Stackoverflow
Solution 1 - JavascriptBrunoLMView Answer on Stackoverflow
Solution 2 - JavascriptPhrogzView Answer on Stackoverflow