Skip to content

Instantly share code, notes, and snippets.

@dei-biz
Created March 22, 2019 09:48
Show Gist options
  • Select an option

  • Save dei-biz/112c3825b5752c76dcb0a915b49bca47 to your computer and use it in GitHub Desktop.

Select an option

Save dei-biz/112c3825b5752c76dcb0a915b49bca47 to your computer and use it in GitHub Desktop.
Execute a function every N minutes at even hour divisions. I.E: 10:00, 10:15, 10:30, 10:45, 11:00 etc
/*receives a function and an integer between 1 and 60. Executes the function every N minutes at even hour divisions*/
const executeEveryNMinutes = (callback, minutes)=>{
if (!(Number.isInteger(minutes) && minutes>0 && minutes<60 && typeof(callback) == "function")){
return false;
}
const now = new Date();
const nextTime = new Date(now.getTime() + minutes * 60 * 1000 + 1);
const nextTimeRound = new Date(nextTime
.setMinutes(minutes*(Math.floor((nextTime.getMinutes() / 60) * (60/minutes)))))
.setSeconds(0)
const timeout = nextTimeRound - now;
console.log(`Releasing the Kraken (again) at ${new Date(nextTimeRound)}`);
setTimeout(()=>{
callback();
executeEveryNMinutes(callback, minutes);
}, timeout)
}
executeEveryNMinutes(() => {console.log("RELEASED!")}, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment