我想要的是Javascript中的计时器每天凌晨2点关闭一次,当计时器关闭时会有警报。我只是不确定该怎么做。
P.S。我在Javascript上很糟糕,所以如果你能把整个剧本留下来,不仅仅是做什么:)
答案 0 :(得分:1)
对于将来在特定时间发出提示的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>
答案 1 :(得分:1)
这应该有用。
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();