Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js/jquery: scheduling events

I want to schedule events, that will fire and call my predefined callback

How can schedule in js / jquery:

  1. one time event?
  2. recurring event (to call my function every minute, or five minutes)?
like image 508
shealtiel Avatar asked Jul 25 '26 15:07

shealtiel


2 Answers

You want setTimeout for a one time event and setInterval for a repeating event.

Both take two arguments: a function and an interval of time specified in milliseconds.

var delay_millis = 1500;

//will alert once, at least half a second after the call to setTimeout
var onceHandle = window.setTimeout(function() {
  alert("Time has passed!");
}, delay_millis);

//will alert again and again
var repeatHandle = window.setInterval(function() {
  alert("Am I annoying you yet?");
}, delay_millis);

Bonus: if you keep around the values returned by calling these functions, you can cancel the callback if you need to.

var shutUpShutUp = function() {
  window.clearInterval(repeatHandle);
};

shutUpShutUp(); //now I can hear myself think.
like image 137
ellisbben Avatar answered Jul 28 '26 05:07

ellisbben


jQuery has nothing to do with it. You need JavaScript timers: setTimeout() and setInterval()

like image 24
Diodeus - James MacFarlane Avatar answered Jul 28 '26 04:07

Diodeus - James MacFarlane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!