简体   繁体   中英

How to call a function/notification at specific offset/interval durations in JavaScript?

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?

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM