Date对象
Date.now() 返回自 1970 年 1 月 1 日 00:00:00 (UTC) 到当前时间的毫秒数
var time = new Date()
var year = time.getFullYear()
var month = time.getMonth() + 1
var day = time.getDate()
var hour = time.getHours()
var minutes = time.getMinutes()
var second = time.getSeconds()
var millSecond = time.getMilliseconds() 毫秒
var timer = time.getTime()
var week = time.getDay()
日期格式化
<script>
Date.prototype.format = function(fmt) {
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()
}
if(/(Y+)/.test(fmt)){
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substring(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]).substring(("" + o[k]).length)));
}
}
return fmt;
}
</script>
定时器
- 缺陷:定时器不准
- 原因:js单线程,在执行每个js任务都是按‘轮转时间片’进行排列,等待执行。定时器就是按照设定的时间将任务放到队列中排队等待被执行,存在等待时间,因此不准。(事件轮循)
设置定时器:var timer = setInterval(fn, delay)
清除定时器:clearInterval(timer)
var timer = setTimeout(fn, delay)
clearTimeout(timer)
防抖
- 一段时间内,以最后一次为准
- 应用:搜索框,通过@input去监听,可以使用防抖,避免频繁触发
function debounce(fn, delay) {
var timer = null;
return function () {
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay)
}
}
节流
- 每隔一段时间,执行一次
- 应用:监听滚动条滚动事件,每隔一段时间执行一次
function throttle(fn, delay) {
var timer = null
return function () {
if (timer) {
return
} else {
timer = setTimerout(() => {
fn.apply(this, arguments)
}, delay)
}
}
}