How can a Bacon.interval be stopped?

114 views Asked by At

I have an event that is fired periodically:

let periodicEvent = Bacon.interval(1000, {});
periodicEvent.onValue(() => {
    doStuff();
});

What I would like is to pause and restart periodicEvent when I need it. How can periodicEvent be paused and restarted? Or is there a better way to do it with baconjs?

1

There are 1 answers

1
Bless Yahu On BEST ANSWER
  1. An impure way to do it is to add a filter that checks for a variable before you subscribe, and then change the variable when you don't want the subscribed action to occur:

    var isOn = true;
    periodicEvent.filter(() => isOn).onValue(() => {
          doStuff();
    });
    
  2. A "pure-r" way to do it would be turn an input into a property of true/false and filter you stream based on the value of that property:

    // 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);
    });
    

Here is a jsbin of the above code

There might be an even better/fancier way of doing it using Bacon.when, but I'm not at that level yet. :)