时间倒计时提醒
var countDown = function (minute, callback) { var allSecond = minute * 60; var tickTimer = null; var start = function() { tickTimer = setInterval(()=>{ -- allSecond; if (allSecond == -1) { stop(); callback && callback('finish'); } else { extract(allSecond); }; }, 1000); }; var extract = function(second) { var m = Math.floor(second / 60), s = second % 60; if (m > 0) { callback && callback('value', `${m} 分 ${s} 秒`); } else { callback && callback('value', `${s} 秒`); }; }; var stop = function() { clearInterval(tickTimer); }; return { start: start, stop: stop }; }; var diffTime = function() { var endTime, waitMinute; // 当前时间和设定时间的差值(分钟) endTime = getSameDay().concat(...arguments); return getMinByMil(); function getSameDay() { var time = new Date(); var year = time.getFullYear(), mon = time.getMonth(), day = time.getDate(); return [year, mon, day]; }; function getMinByMil(mil) { var endTimeMs = new Date(...endTime).getTime(); waitMinute = Math.ceil((endTimeMs - new Date().getTime()) / 1000 / 60); return waitMinute; }; }; // 比如当前时间为15: 58你设置为16:00:01做某件事,则可以这样 var time = diffTime(16, 00, 1); countDown(time, function(state, v) { if (state === 'finish') { console.log('时间到'); } else if (state === 'value') { console.log(v); }; }).start();
开心的做一个无忧无虑的码农,争取每天进步一点。