1、防抖
定义:触发某个事件,延迟n秒后执行,若n秒内再次触发该事件则重新计时
实现方法:利用定时器来控制当前时间是否过了n秒,过了则执行实际,否则清除定时器重新计时
<body>
<input type="text" id="debounce">
<script>
let ipt = document.querySelector('#debounce')
ipt.addEventListener('keyup', function (e) {
_debounce.call(this,e.target.value)
})
function ajax(row) {
console.log(row)
}
function debounce(fun,delay) {
let timeId
return function () {
let args = arguments
let that = this
clearTimeout(timeId) // 定时器未消失则清除,重新计时
timeId = setTimeout(function () {
fun.apply(that,args)
},delay)
}
}
var _debounce = debounce(ajax,2000)
</script>
</body>
1、节流
定义:事件的触发n秒内只能执行一次
实现方法:判断当前时间是否过了n秒,过了则可以再次执行该事件。
<body>
<button>节流</button>
<script>
var btn = document.querySelector('button')
btn.addEventListener('click', function () {
_throttle.call(this,this.innerHTML)
})
var _throttle = throttle(ajax,2000)
function throttle(fun,delay) {
let timeidd, old = 0
// 定时器方式
// return function () {
// let args = arguments
// let that = this
// if(!timeidd) {
// timeidd = setTimeout(function () {
// timeidd = null
// fun.apply(that, args)
// },delay)
// }
// }
// 时间戳方式
return function () {
let now = new Date().valueOf()
let args = arguments
let that = this
if(now-old> delay) {
fun.apply(that, args)
old = now
}
}
}
</script>
</body>
应用场景
防抖(debounce):
1、输入框,例如用户不断输入后200毫秒调用查询服务。 2、改变窗口大小事件,window.resize时,只出发一次。
防抖(throttle):
1、按钮,防止按钮不停触发后端服务。 2、滚动事件等