[英]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.
例如:计划值是8s、14s、20s,那么第一个通知将在 8s 后发送,下一个是 14s,最后一个是 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.
对于您的用例,setTimeout 是唯一的选择,因为您需要在不同的时间间隔调用通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.