feat: 添加首次会执行的防抖
This commit is contained in:
parent
47d42c3482
commit
78fa340090
22
html/防抖.html
22
html/防抖.html
@ -9,7 +9,6 @@
|
||||
<div>
|
||||
<input type="text" id="input">
|
||||
<p></p>
|
||||
<input type="button" id="button">
|
||||
</div>
|
||||
<script>
|
||||
function deBounce(fun, delay){
|
||||
@ -23,11 +22,30 @@
|
||||
},delay)
|
||||
}
|
||||
}
|
||||
|
||||
function deBounce2(fun, delay){
|
||||
var timer = 0
|
||||
var flag = true // 是否允许执行
|
||||
return function(){
|
||||
var args = arguments
|
||||
var context = this
|
||||
if(flag) {
|
||||
fun.apply(context, args)
|
||||
flag = false
|
||||
return
|
||||
}
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(function(){
|
||||
fun.apply(context, args)
|
||||
flag = true
|
||||
},delay)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<script type="text/javascript">
|
||||
let input = document.querySelector("input")
|
||||
let p = document.querySelector("p")
|
||||
input.addEventListener("input", deBounce(function(){
|
||||
input.addEventListener("input", deBounce2(function(){
|
||||
p.innerHTML = this.value
|
||||
}
|
||||
, 250))
|
||||
|
17
js/防抖.js
17
js/防抖.js
@ -15,3 +15,20 @@ export default function deBounce(fun, delay) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 首次执行版本
|
||||
* @param { Function } - 需要添加防抖功能的函数
|
||||
* @delay { number } - 防抖延迟的时间
|
||||
*/
|
||||
export default function deBounce(fun, delay) {
|
||||
var timer = 0
|
||||
return function() {
|
||||
var args = arguments
|
||||
var context = this
|
||||
if(timer) clearTimeout(timer)
|
||||
timer = setTimeout(function(){
|
||||
fun.apply(context, args)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user