Search code examples
javascriptpromiseasync-awaitevent-loop

Convert setInterval to promise


Hello I'm new to javascript and wondering if there is a way to covnert below setInterval thingy into a promise so that .then could be used instead of the callback. Any help?

My ideas:
With a setTimeout I could resolve after a fixed time. But I'm not getting any ideas dealing with setInterval...

function alert_above(scrip, price, callback) {
  var intvl = setInterval(() => {
    if (get_last_price(scrip) > price) {
      callback();
      clearInterval(intvl);
    }
  }, 1000);
 return intvl;
}


Solution

  • I think you could wrap into a new Promise like :

    function promisifySetInterval(time) {
      var defer = new Promise(resolve => {
        let counter = 0
        var intvl = setInterval(() => {
          if (counter > time) {
            resolve('hey');
            clearInterval(intvl);
          } else {
            counter += 1000
          }
        }, 1000);
      })
     return defer;
    }
    
    promisifySetInterval(2000).then(param => {
      console.log('hey', param)
    })

    And for youre case something like this :

    function alert_above(scrip, price) {
      var defer = new Promise(resolve => {
        var intvl = setInterval(() => {
          if (get_last_price(scrip) > price) {
            resolve('hey');
            clearInterval(intvl);
          }
        }, 1000);
      })
     return defer;
    }
    
    alert_above().then(param => {
      console.log('hey', param)
    })