Javascript 怎样才能阻止咸肉的间歇?

Javascript 怎样才能阻止咸肉的间歇?,javascript,bacon.js,Javascript,Bacon.js,我有一个定期触发的事件: let periodicEvent = Bacon.interval(1000, {}); periodicEvent.onValue(() => { doStuff(); }); 我希望在需要时暂停并重新启动periodicEvent。如何暂停和重新启动PeriodiceEvent?或者有没有更好的方法来使用baconjs 一种不纯的方法是添加一个过滤器,在订阅之前检查变量,然后在不希望订阅操作发生时更改变量: var isOn = true; per

我有一个定期触发的事件:

let periodicEvent = Bacon.interval(1000, {});
periodicEvent.onValue(() => {
    doStuff();
});
我希望在需要时暂停并重新启动
periodicEvent
。如何暂停和重新启动PeriodiceEvent?或者有没有更好的方法来使用baconjs

  • 一种不纯的方法是添加一个过滤器,在订阅之前检查变量,然后在不希望订阅操作发生时更改变量:

    var isOn = true;
    periodicEvent.filter(() => isOn).onValue(() => {
          doStuff();
    });
    
  • “pure-r”方法是将输入转换为true/false属性,并根据该属性的值过滤流:

    // make an eventstream of a dom element and map the value to true or false
    var switch = $('input')
        .asEventStream('change')
        .map(function(evt) {
            return evt.target.value === 'on';
        })
        .toProperty(true);
    
    
    var periodEvent = Bacon.interval(1000, {});
    
    // filter based on the property b to stop/execute the subscribed function
    periodEvent.filter(switch).onValue(function(val) {
        console.log('running ' + val);
    });
    

  • 也许有更好/更奇特的方法可以使用,但我还没有达到这个水平。:)

    whenneed
    也是培根流/财产吗?绝对不要做不纯的版本,基于财产的过滤是正确的方法。