防抖节流实践及vue中使用
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
最近发现在网络慢情况,或并发高情况下,未使用防抖节流导致出现一定性能问题
一、防抖节流理解
防抖:在一段时间内连续点击触发方法,每次触发会重新计时,最常用场景:在文本框输入值立马去后台查询数据,频繁调用后台造成性能问题,可以使用防抖,在一定时间内只去后台查询一次。( echart图表监听窗口改变重新渲染、滚动事件、滑动事件)
节流:在一段时间内连续点击触发方法,在这段时间内只执行一次,不会去重新计时,最常用场景:去请求接口数据。或者更新数据,可以使用节流,保证在(假设一秒内)只执行一次查询,或者更新操作
二、代码示例
1.演示地址
2.vue中使用防抖节流
代码如下(示例):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="viewport-fit=cover,width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
</head>
<body>
<div id="main">
<button @click="click1">不使用防抖({{count1}})</button>
<button @click="click2">使用防抖({{count2}})</button>
<button @click="click3">不使用节流({{count3}})</button>
<button @click="click4">使用节流({{count4}})</button>
</div>
</body>
<script src="http://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
//节流
throttle = function (f, t, im ){
if(!t) t = 1000;
var flag = true;
im = typeof(im) == "undefined" ? true : im
return function (){
if(flag){
flag = false
im && f.apply(this,arguments)
setTimeout(() => {
!im && f.apply(this,arguments)
flag = true
},t)
}
}
}
//防抖 一般用于input实时查询后台接口 isLoad=true 是否立即执行一次
debounce = function(func,wait,immediate) {
var timeout;
wait = wait||1000
immediate = typeof(immediate) == "undefined" ? true : immediate
return function () {
var context = this;
var args = arguments;
// 防抖函数的代码使用这两行代码来获取 this 和 参数,是为了让 debounce 函数最终返回的函数 this 指向不变以及依旧能接受到 e 参数。
if (timeout) clearTimeout(timeout);
if (immediate) { // 立即执行
var callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
}
else { // 非立即执行
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}
}
new Vue({
el:'#main',
data(){
return {
count1:0, count2:0, count3:0, count4:0
}
},
methods:{
click1(){
console.log("不使用防抖=>",new Date().getTime())
this.count1 ++;
},
click2:debounce(function(){
console.log("使用防抖=>",new Date().getTime())
this.count2 ++;
}),
click3(){
console.log("不使用节流=>",new Date().getTime())
this.count3 ++;
},
click4:throttle(
function(){
console.log("使用节流=>",new Date().getTime())
this.count4 ++;
}
)
}
})
</script>
</html>
三、总结
防抖节流能够提高性能,在高并发情况下能够减少后台请求访问量