如何在时间到达特定时间时触发功能 [英] How do I trigger a function when the time reaches a specific time

查看:146
本文介绍了如何在时间到达特定时间时触发功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在时间到达下午3:00时触发javascript函数。

I want to trigger a javascript function when the time reaches, say, 3:00 PM.

时间将动态分配。那么有没有任何javascript函数来实现?

The time will be assigned dynamically. So is there any javascript function to achieve that??

推荐答案

你只需要计算当前时间和目标之间的差异时间和使用 setTimeout() 具有该值。

You just need to calculate the difference between the current time and the target time and use setTimeout() with that value.

例如,根据目标浏览器解析日期的方式,您可以执行以下操作:

For example, depending on how your target browsers parse dates, you could do the following:

function alert3pm() {
  alert("It's 3PM!");
}
var timeAt3pm = new Date("1/31/2011 03:00:00 PM").getTime()
  , timeNow = new Date().getTime()
  , offsetMillis = timeAt3pm - timeNow;
setTimeout(alert3pm, offsetMillis);

或者更确切地说,解析日期(因为浏览器之间真的不一致)你可以做类似的事情这个:

Or rather, instaed of parsing a date (since that's really inconsistent between browsers) you could do something like this:

function getTimeAtHour(hour) {
  var t = new Date();
  t.setHours(hour);
  t.setMinutes(0);
  t.setSeconds(0);
  t.setMilliseconds(0);
  return t;
}

这篇关于如何在时间到达特定时间时触发功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆