(一)防抖: 在一定时间间隔中重复点击,只执行最后一次; 如搜索框中,搜索的字符变动,当变动的时间间隔在0.5秒内时不执行查询,
打字最后一次停顿超过0.5s时才查询。采取频繁触发的最后一次操作
// 案例:
<template>
<a-input-search v-model:value="searchValue" placeholder="搜索"
@change="onSearch(searchValue)" />
</template>// html的搜索框
<script>
const debounce = (func, wait) => {
let timeout // 定义一个变量,作为初始化时间
return function () { // 返回执行防抖的方法
const context = this // 保存原函数的this上下文
const args = arguments // 保存原函数的参数
clearTimeout(timeout)
timeout = setTimeout(() => {
func.apply(context, args) // 用于调用一个具有给定 this 值的函数
}, wait)
}
}
const onSearch = debounce((value) => {
getAreaList(value)
}, 500 )
</script>
// 简化代码:
<template>
<a-input-search v-model:value="searchValue" placeholder="搜索"
@change="onSearch(searchValue)" /> // html的搜索框
</template>
<script>
const debounce = (func, wait) => {
let timeout // 定义一个变量,作为初始化时间
return function () { // 返回执行防抖的方法
clearTimeout(timeout)
timeout = setTimeout(() => {
func.apply(this, arguments)// 用于调用一个具有给定 this 值的函数
}, wait)
}
}
const onSearch = debounce( (value) => {getAreaList(value)}, 500 )
</script>
(二)节流:在一定时间间隔中重复点击,只执行第一次操作;
// 案例:
<script>
const throttle = (func, delay) => {
let lastCall = 0
return function (...args){
const now = new Date().getTime()
if (now - lastCall < delay) { // 比较距离上一次触发的时间
return
}
lastCall = now
return func(...args)
}
}
// 使用
window.addEventListener('resize', throttle(function() {
console.log('窗口大小已改变');
}, 1000))
</script>