整分
let timer = null
function timeFunc() {
const date = new Date()
// 取目前分鐘個位數,友善計算
const mins = date.getMinutes() % 10
// 觸發時間:10 - mins 求出剩餘時間
const ticktack = (10 - mins) * 60 * 1000
timer = setTimeout(timeFunc, ticktack)
if (mins == 0) {
console.log('整分了')
}
}
timeFunc()
指定時間
let timer = null
function timeFunc() {
const date = new Date()
const hours = date.getHours()
const mins = date.getMinutes()
const now = date.getTime()
const targetTime = new Date().setHours(8, 30, 0)
/**
* 剩餘時間
* 大于目前時間 時間未到,減去目前時間即可
* 小于目前時間 時間已過,+24小時減去目前時間
*/
let remTime = targetTime >= now ? (targetTime - now) : (targetTime + 86400000 - now)
timer = setTimeout(timeFunc, remTime)
if (hours === 8 && mins === 30) {
console.log('8:30了')
}
}
timeFunc()