js/jquery:调度事件

she*_*iel 2 javascript events

我想安排事件,这将触发并调用我预定义的回调

如何在js/jquery中安排:

  1. 一次性活动?
  2. 反复发生的事件(每分钟或五分钟呼叫我的功能)?

ell*_*ben 6

您想要 setTimeout一次性事件和 setInterval重复事件.

两者都有两个参数:一个函数和一个以毫秒为单位指定的时间间隔.

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);
Run Code Online (Sandbox Code Playgroud)

额外奖励:如果您通过调用这些函数来保留返回的值,则可以根据需要取消回调.

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

shutUpShutUp(); //now I can hear myself think.
Run Code Online (Sandbox Code Playgroud)