强制setInterval进入循环的下一步

时间:2018-03-02 18:58:46

标签: javascript node.js

是否可以强制setInterval像这样进入下一步?:

global.timers = [] ;

var index = global.timers.length ;

global.timers[index] = setInterval(()=>{
      // ...
},15000);

// pseudo code 
if (event1 occured)
     global.timers[x].step++ // Don't wait for remained time and go to next tick

2 个答案:

答案 0 :(得分:0)

您可以将id存储在timers数组中并提取事件处理函数,然后您可以更好地控制何时调用事件处理程序。

  1. 为事件
  2. 创建处理函数
  3. 当推送到全局计时器数组时,请记住存储名称和计时器ID。
  4. 如果在通过setInterval调用计时器之前发生了事件,请停止计时器并直接调用处理程序。
  5. 示例:

    function coolEventHandler () {
      console.log('handling cool event');
    }
    
    timers[0] = { name: 'coolEvent', id: setInterval(coolEventHandler, 15000) };
    
    if('coolEvent') {
      // find the correct timer
      timer = timers.find(t => t.name === 'coolEvent');
      // stop the timer so the callback is never invoked
      // you probably want to remove it from the global timers array here too.
      clearInterval(timer.id);
      // call the handler directly
      coolEventHandler();
     }
    

答案 1 :(得分:0)

您可以简单地清除间隔并再次创建

global.timers = [] ;

var index = global.timers.length ;

global.timers[index] = setInterval(fn,15000);

// pseudo code 
if (event1 occured) {
    clearInterval(global.timers[x]);
    global.timers[index] = setInterval(fn,15000);
}
function fn() {

}