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

发布于 2025-01-31 09:03:21 字数 125 浏览 4 评论 0原文

在我最近的项目中,我遇到了一个情况,必须根据特定时间表向客户发送通知。例如:时间表值是 8s,14s,20s ,然后在8s之后发送第一次通知,接下来是在14s上,最后一个是20s。 我们如何实现此功能?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心的憧憬 2025-02-07 09:03:21

我会做这样的事情:

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

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();
蓝戈者 2025-02-07 09:03:21

您可以做类似的事情:

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是唯一的选项,因为您需要在不同的间隔内调用通知。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文