1.防抖(debounce)
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时;典型的案例就是输入搜索:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时。
通俗理解,就是我们在点击请求或者点击加载等过程中,只需要点击一次,但由于请求慢,点击了好多次,导致多次请求,防抖就是在点击了好多次之后的最后一次才会请求。
在一些搜索框输入内容时,会有好多联想词在下方显示出来,并不是输入框内容一改变就触随即弹出联想词的,是我们结束输入后,经过一段时间,才会触发。
例:
<template>
<u-search
shape="square"
:showAction="false"
height="77rpx"
searchIconSize="40"
placeholder="搜索科普内容"
v-model="params.keyword"
clearabled
@change="searchData()"
@search="searchData()"
></u-search>
</template>
let time;
export default {
methods: {
// 查询(防抖)
searchData() {
let that = this;
if (time) {
clearTimeout(time);
}
time = setTimeout(function () {
that.params.pageNum = 1;
that.getScienceLisy();
time = null;
}, 1000);
},
}
}
2.节流(throttle)
规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效; 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>节流</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
<button @click="thr">点击</button>
<div>实际点击:{{clicknumber}}</div>
<div>有效点击:{{num}}</div>
</div>
<script>
let time
let lastTime
var app=new Vue({
el:'#app',
data:{
num:0,
clicknumber:0
},
methods: {
thr: function () {
this.clicknumber++
let that = this
let now = new Date();
if (lastTime && now - lastTime < 2000) {
clearTimeout(time)
}
time = setTimeout(function () {
that.num++
console.log('点击了'+that.num+'次')
lastTime = new Date()
}, 500)
}
}
})
</script>
</body>
</html>
区别:
防抖是将多次执行变为最后一次执行,节流是将多次执行变成每隔一段时间执行