js实现定时提醒

使用 setTimeout 实现单次提醒
function setReminder(message, delay) {
setTimeout(() => {
alert(message);
}, delay * 1000); // 将秒转换为毫秒
}
// 示例:5秒后提醒
setReminder("该休息了!", 5);
使用 setInterval 实现周期性提醒
let reminderInterval;
function startPeriodicReminder(message, interval) {
reminderInterval = setInterval(() => {
alert(message);
}, interval * 1000);
}
function stopPeriodicReminder() {
clearInterval(reminderInterval);
}
// 示例:每10秒提醒一次
startPeriodicReminder("喝水时间到!", 10);
// 停止提醒
// stopPeriodicReminder();
使用 Notification API 实现桌面通知
function showNotification(title, options) {
// 检查浏览器是否支持通知
if (!("Notification" in window)) {
alert("该浏览器不支持桌面通知");
return;
}
// 检查是否已授予权限
if (Notification.permission === "granted") {
new Notification(title, options);
} else if (Notification.permission !== "denied") {
Notification.requestPermission().then(permission => {
if (permission === "granted") {
new Notification(title, options);
}
});
}
}
// 示例:显示通知
showNotification("提醒", {
body: "任务已完成",
icon: "path/to/icon.png"
});
结合使用定时器和通知
function setSmartReminder(message, delay) {
setTimeout(() => {
showNotification("提醒", { body: message });
}, delay * 1000);
}
// 示例:30秒后发送通知
setSmartReminder("会议即将开始", 30);
添加声音提醒
function playAlertSound() {
const audio = new Audio('path/to/sound.mp3');
audio.play();
}
function setReminderWithSound(message, delay) {
setTimeout(() => {
alert(message);
playAlertSound();
}, delay * 1000);
}
// 示例:带声音的提醒
setReminderWithSound("时间到了!", 60);
