In my recent project, I came across a situation where I have to send a notifications to client based on specific schedule. For an example: schedule value is 8s,14s,20s then first notification will be send after 8s, next is on 14s and last is on 20s. How can we achieve this functionality?
CodePudding user response:
I would do something like this:
function scheduleNotification(seconds){
setTimeout(function(){
// your logic here
// you could also pass a callback to be executed here
}, seconds * 1000);
}
function sendNotifications(){
scheduleNotification(8);
scheduleNotification(14);
scheduleNotification(20);
}
sendNotifications();
CodePudding user response:
You can do something like this:
const intervalDuration = [8, 14, 20]; // you can add or delete intervals
for (let i = 0, len = intervalDuration.length; i < len; i ) {
setTimeout(\* function *\, intervalDuration[i] * 1000);
}
Here, you can add multiple interval based on your requirement. For your use case, setTimeout is the only option as you need to call notifications on different intervals.