我如何制作一个一天响一次的Javascript计时器

我如何制作一个一天响一次的Javascript计时器,javascript,web,timer,alert,Javascript,Web,Timer,Alert,我想要的是一个Javascript中的计时器,每天凌晨2:00响起一次,当计时器响起时会发出警报。我只是不知道该怎么做 另外,我对Javascript很在行,所以如果你能留下整个脚本,而不仅仅是做什么:)对于一个Javascript网页,在将来的某个特定时间出现提示,你必须让浏览器在显示该页面的情况下运行。浏览器中网页的Javascript仅在浏览器中当前打开的页面中运行。如果这真的是你想要做的,那么你可以这样做: // make it so this code executes when yo

我想要的是一个Javascript中的计时器,每天凌晨2:00响起一次,当计时器响起时会发出警报。我只是不知道该怎么做


另外,我对Javascript很在行,所以如果你能留下整个脚本,而不仅仅是做什么:)

对于一个Javascript网页,在将来的某个特定时间出现提示,你必须让浏览器在显示该页面的情况下运行。浏览器中网页的Javascript仅在浏览器中当前打开的页面中运行。如果这真的是你想要做的,那么你可以这样做:

// make it so this code executes when your web page first runs
// you can put this right before the </body> tag

<script>
function scheduleAlert(msg, hr) {
    // calc time remaining until the next 2am
    // get current time
    var now = new Date();

    // create time at the desired hr
    var then = new Date(now);
    then.setHours(hr);
    then.setMinutes(0);
    then.setSeconds(0);
    then.setMilliseconds(0);

    // correct for time after the hr where we need to go to next day
    if (now.getHours() >= hr) {
        then = new Date(then.getTime() + (24 * 3600 * 1000));    // add one day
    }

    // set timer to fire the amount of time until the hr
    setTimeout(function() {
        alert(msg);
        // set it again for the next day
        scheduleAlert(msg, hr);
    }, then - now);
}

// schedule the first one
scheduleAlert("It's 2am.", 2);
</script>
//使此代码在网页首次运行时执行
//你可以把这个放在标签前面
功能计划警报(消息、人力资源){
//计算到下一个凌晨2点的剩余时间
//获取当前时间
var now=新日期();
//以所需的人力资源创建时间
var then=新日期(现在);
然后,设定小时数(hr);
然后,设置分钟数(0);
然后。设置秒(0);
然后,设置毫秒(0);
//更正为人力资源部之后我们第二天需要去的地方
如果(now.getHours()>=hr){
then=新日期(then.getTime()+(24*3600*1000));//添加一天
}
//设置定时器,以触发时间量,直到hr
setTimeout(函数(){
警报(msg);
//第二天再定一次
scheduleAlert(消息、人力资源);
},当时—现在);
}
//安排第一个
scheduleAlert(“现在是凌晨2点。”,2);
这应该行得通

function alarm() {
  alert('my alert message');
  setAlarm();
}

function setAlarm() {
  var date = new Date(Date.now());
  var alarmTime = new Date(date.getYear(), date.getMonth(), date.getDate(), 2);
  if (date.getHours() >= 2) {
    alarmTime.setDate(date.getDate() + 1);
  }
  setTimeout(alarm, alarmTime.valueOf() - Date.now());
}
setAlarm();

欢迎来到;请复习一下。重要的是显示,以便我们可以给你更好的上下文信息。你会留下一个电脑浏览器运行24/7只是为了闪亮的消息在午夜?我错过了什么吗?使用setTimeout,每小时触发一次偏差(每小时触发一次,以说明日光或时间变化);如果时间正确,请运行所述任务。也就是说,我不确定它有多实用..检查现在是什么时间,
var date=new date();date.getHours()
请注意,
setTimeout
在数小时内非常不准确。另外,要增加一天,你真的应该增加一天,而不是增加86400000毫秒。@Bergi-如果
setTimeout()
不完全准确,你有更好的解决方案来回答这个问题吗?正如@user2246674所建议的,你可以使用多个较小的超时来自我调整。然而,实际上,我现在不确定
setTimeout
的不准确性是一般的还是仅适用于(未调整的)序列+1对于工作解决方案:-)
setAlarm
不在
alarm
的范围内。还有,为什么要超时1秒?@Bergi-你说的范围是对的。而且,没有什么理由需要额外的超时,尤其是在警报阻塞的情况下。编辑。