这是我参与更文挑战的第10天,活动详情查看: 更文挑战
『JavaScript中的防抖与节流』的初体验
什么是防抖和节流?
相信大家在日常学习中 一定不是第一次听说这两个名词了, 那么到底什么是 防抖和节流呢?
防抖(debounce)当事件被触发时,设定一个周期延迟执行动作,若期间又被触发,则重新设定周期,直到周期结束,执行动作。
节流(throttle)固定周期内,只执行一次动作,若有新事件触发,不执行。周期结束后,又有事件触发,开始新的周期。 唠了半天的基本概念,那么我们就来实际操作一番吧~。
防抖的初体验
首先 我们看一下 初始代码
<body>
没有 防抖函数的输入框: <input class="input"/>
</input>
</body>
<script>
let input =document.querySelector('.input');
function ajax(content) {
console.log("发送了网络请求", content);
}
input.addEventListener('keyup', (e) => {
ajax(e.target.value)
})
//这时如果 我们使用键盘在input狂内进行输入就会在调用很多次 Ajax函数,而且这时候的调用 是没有任何意义的。
</script>
接下来 我们 写一个debounce函数
function debounce(fun, timer) {
return function (args) {
let that = this
let _args = args
fun.id = setTimeout(function(){
fun.call(that, _args)
}, timer)
}
}
let debounceAjax = debounce(ajax, 500)
input.addEventListener('keyup', function(e) {
debounceAjax()
})
//申明一个函数 并让其 调用另一个函数 形成闭包。并且 在 另一个 函数里面 有一个500毫秒的定时器,
//当 函数在被调用的时候 会出发定时器在发送Ajax请求,但是如果在 这 500毫秒内 函数 在此 被调用 那么 就会 清楚 上一个定时器, 时间再次清零。直到下一次定时器时间没有被打断为止。
与节流的相遇
废话不多说 直接上代码
function throttle(fun, timer) {
let last, deferTimer
return function (args) {
let that = this
let _args = arguments
let now = +new Date()
if(last && now < last + timer){
clearTimeout(deferTimer)
deferTimer = setTimeout(function(){
fun.call(that, _args)
}, timer)
}else{
last = now
fun.call(that, _args)
}
}
}
let throttleAjax = throttle(ajax, 500)
//首先函数 被调用 二话不说 直接last 由于没有找到 那么 last = now,并且 调用函数 发送ajax请求,之后 函数 throttle函数 在慈悲调用 进行 对比 如果 last 或者now 大于 我现在的500毫秒 那么 清楚定时器 并且 于此同时 在创建一个定时器发送Ajax请求