繁体   English   中英

如何在 JavaScript 中以特定的偏移量/间隔持续时间调用函数/通知?

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

在我最近的项目中,我遇到了一种情况,我必须根据特定的时间表向客户发送通知。 例如:计划值是8s、14s、20s,那么第一个通知将在 8s 后发送,下一个是 14s,最后一个是 20s。 我们怎样才能实现这个功能呢?

我会做这样的事情:

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

你可以这样做:

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

在这里,您可以根据需要添加多个间隔。 对于您的用例,setTimeout 是唯一的选择,因为您需要在不同的时间间隔调用通知。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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