javascriptcocos2d-js

running async function once every minute


I was planning to get a data from the server every minute. However, if I run this code, this function is being called repeatedly. On the other hand, if I added date.getMilliseconds == 0 in the condition, it won't process any results. Do you have any suggestions on how to run the function once every 1 minute?

async update() {
 var date = new Date();
 if (date.getSeconds() == 0) {
   var newdata = await getData(1);
   array.shift();
   array.push(newdata); 
  }
}

Solution

  • Since it looks like you don't have fine control over when update is called, one option would be to set a boolean to true every time getSeconds() === 0 (set it to false otherwise), and then only run the real code when the flag is false and getSeconds() === 0:

    let hasRun = false;
    // ...
    async update() {
     var date = new Date();
     const secs = date.getSeconds();
     if (secs !== 0) {
       hasRun = false;
     } else if (secs === 0 && hasRun === false) {
       hasRun = true;
       // your code
       var newdata = await getData(1);
       array.shift();
       array.push(newdata); 
      }
    }
    

    An alternative that might require less resources due to not creating Dates every frame would be to have a separate function that toggles the boolean, set with a setInterval that runs every 60 seconds, no Dates involved:

    let hasRun = false;
    setInterval(() => hasRun = false, 60000);
    async update() {
      if (hasRun) return;
      hasRun = true;
      // your code
    }
    

    (of course, you could also try setInterval(update, 60000) if the framework allows it)