1

I am trying to trigger a new random number every 30 seconds of every minute. I have kind of working. It fires once. How do I rearm my promise after it fires, so it can fire again in 30 seconds?

    let token = new Promise((resolve, reject) => {
      let id = setInterval(function() {
        let sec = new Date().getSeconds()
        if ( sec === 0 || sec === 30 ) {
            setInterval(getToken, 30000);
            getToken();        
            clearInterval(id);
        }
      },1000);

      function getToken(){
        token = Math.random()
        resolve(token)
      }
    })

    console.log(await token)
Dshiz
  • 3,099
  • 3
  • 26
  • 53
  • Why do you need this to be a `Promise`? – goto Dec 31 '21 at 13:57
  • I'm trying to return `token` as a callback in a higher scoped function. – Dshiz Dec 31 '21 at 13:58
  • 3
    Once a promise has been settled (resolved or rejected) it's done, you can't rearm/reset it. Why not make `token` a function that returns a promise? Or use a [generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator). – robertklep Dec 31 '21 at 13:59
  • What is the ultimate goal here? Do you want to generate a new token every 30 seconds then save it somewhere? – goto Dec 31 '21 at 14:05
  • @goto1 yes, essentially.. I need the token variable available as it changes. MDN has an example of using promises with setInterval, but it's kind of confusing and not directly applicable because I'm using both setInterval and setTimeout – Dshiz Dec 31 '21 at 14:06
  • Why not just use `setInterval` that updates a `token` variable every 30 seconds? I don't see why you'd want a `Promise` here – goto Dec 31 '21 at 14:10
  • I'm running into scope issues if I don't `Promise`. I need `token` available outside of setInterval. The code as written works correctly, but only once. I need it to work every 30 seconds – Dshiz Dec 31 '21 at 14:13
  • @robertklep A generator sounds interesting.. I will look into this. Thank you! – Dshiz Dec 31 '21 at 14:28
  • 1
    Do you expect the single statement `console.log(await token)` to log multiple tokens? That's not how promises work, you can only resolve them once. – Bergi Dec 31 '21 at 14:31
  • @robertklep I find myself stuck in scope hell with a generator also. – Dshiz Dec 31 '21 at 16:16
  • It doesn't solve my issue. I will create a new question once I have time to build it out exactly into a minimal reproducible example. However, I think what I need is clearly described in this question. – Dshiz Dec 31 '21 at 16:47

0 Answers0