简体   繁体   English

Node.js从事件中取消setTimeout

[英]Node.js cancel setTimeout from an event

I have some code that polls a service and I need a way to cancel that interval clearTimeout via events. 我有一些轮询服务的代码,我需要一种通过事件取消该间隔clearTimeout的方法。 The timeouts act as an interval, calling setTimeout again within the function. 超时充当间隔,在函数内再次调用setTimeout。

So for example, I have another object that that's exposed as an event emitter and this process polls and emits some data along the way. 因此,例如,我有另一个对象作为事件发射器公开,并且此过程沿该过程轮询并发射一些数据。 Here's a simplified example: 这是一个简化的示例:

function events() {

  var timer = true;
  events.on('cancel', function() {
    timer = false;
  });

  function polling() {
    //Get some data
    events.emit('data', data);

    if (timer || typeof timer == 'number') {
      timer = setTimeout(polling, 1000);
    }
  }

  polling();

}

This can work, basically when this service receives the cancel event, it sets the timer to false, which due to the check it won't continue. 这可以正常工作,基本上,当此服务接收到cancel事件时,它将计时器设置为false,由于检查它不会继续,因此将其设置为false。 However, there could be a chance where it passed the condition, event fired, timer reset and now it continues on. 但是,它可能会通过条件,事件触发,计时器重置,然后继续运行。

Any idea if there's a more bulletproof way to handle this kind of thing? 是否知道是否有更防弹的方式来处理此类事情? Basically canceling the polling based on an event. 基本上取消基于事件的轮询。

However, there could be a chance where it passed the condition, event fired, timer reset and now it continues on. 但是,它可能会通过条件,事件触发,计时器重置,然后继续运行。

Nope. 不。 Node.js is single-threaded and works by means of an event loop, so nothing can interrupt your running code unless you allow it to (by queuing up and continuing execution in another event, eg with setTimeout or process.nextTick ). Node.js是单线程的,并且通过事件循环工作,因此除非您允许它(通过在另一个事件中排队并继续执行,例如,使用setTimeoutprocess.nextTick ),否则没有任何东西可以中断正在运行的代码。

What you should do instead if you want to avoid one more call of polling , though, is use clearTimeout . 但是,如果要避免再次调用polling ,应该改用clearTimeout

function events() {
  var timer = null;

  events.on('cancel', function() {
    clearTimeout(timer);
  });

  function polling() {
    //Get some data
    events.emit('data', data);

    timer = setTimeout(polling, 1000);
  }

  polling();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM