天天看点

JavaScript 整分或者指定时间执行操作

整分
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()
           

继续阅读