学无先后,达者为师

网站首页 前端文档 正文

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

作者:ZionHH 更新时间: 2022-05-12 前端文档

整分

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

原文链接:https://blog.csdn.net/z291493823/article/details/122759446

栏目分类
最近更新