定时器:
setInterval() :按照指定的周期(以毫秒计)来调用函数或计算表达式。方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。
setTimeout() :在指定的毫秒数后调用函数或计算表达式,执行一次。
var timer1=window.setTimeout(function(){},1000);
window.clearTimeout(timer1); //->把timer1定时器清除掉.
var timer2 = setInterval(function(){},1000);
window.clearInterval(timer2)
时间日期
// 说明:JS时间Date格式化参数
// 参数:格式化字符串如:'yyyy-MM-dd HH:mm:ss'
// 结果:如2016-06-01 10:09:00
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"H+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
var year = this.getFullYear();
var yearstr = year + '';
yearstr = yearstr.length >= 4 ? yearstr : '0000'.substr(0, 4 - yearstr.length) + yearstr;
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (yearstr + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
计算天数差的函数,通用
//计算天数差的函数,通用
function DateDiff(sDate1, sDate2){ //sDate1和sDate2是2006-12-18格式
var oDate1, oDate2, iDays;
oDate1 = new Date(sDate1).getTime();
oDate2 = new Date(sDate2).getTime();
iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24); //把相差的毫秒数转换为天数
return iDays
}
var myDate = new Date(),
_year = myDate.getFullYear(),
_mont = myDate.getMonth() + 1,
_data = myDate.getDate(),
nowDate = _year + '-' + _mont + '-' + _data, //当前时间
expiryTime = '2020-03-09', //到期时间
remainingTime = DateDiff(nowDate, expiryTime); //剩余天数
vue倒计时
<div > 倒计时:{{countDown(endDate)}}</div>
data() {
return {
now: new Date().getTime(), //当前时间
timer: null // 定时器名称
};
},
computed: {
//计算属性,返回剩余时间
countDown(){
return function(endDate) { // endDate格式"2020-04-15 20:21"
let ctime = this.now
let stime = (new Date(endDate.replace(/-/g, '/'))).getTime()
let cdtime = stime - ctime
let timeData = '00天00小时00分'
if (cdtime > 0) {
let days = parseInt(cdtime / 1000 / 60 / 60 / 24, 10)
days = days < 10 ? '0' + days : days
let hours = parseInt(cdtime / 1000 / 60 / 60 % 24, 10)
hours = hours < 10 ? '0' + hours : hours
let min = parseInt(cdtime / 1000 / 60 % 60, 10)
min = min < 10 ? '0' + min : min
// let sec = parseInt(cdtime / 1000 % 60, 10)
timeData = days + '天' + hours + '小时' + min + '分'
}
return timeData
}
}
},
methods:{
getData(){
// 倒计时处理
clearInterval(this.timer);
this.timer = null;
if(this.liveStatus === '1'){
this.timer = setInterval(()=>{
this.now = new Date().getTime()
},60000)
}
}
},
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}