54 lines
1.2 KiB
HTML
54 lines
1.2 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>防抖</title>
|
|
</head>
|
|
<body>
|
|
<div>
|
|
<input type="text" id="input">
|
|
<p></p>
|
|
</div>
|
|
<script>
|
|
function deBounce(fun, delay){
|
|
var timer = 0
|
|
return function(){
|
|
var args = arguments
|
|
var context = this
|
|
clearTimeout(timer)
|
|
timer = setTimeout(function(){
|
|
fun.apply(context, args)
|
|
},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", deBounce2(function(){
|
|
p.innerHTML = this.value
|
|
}
|
|
, 250))
|
|
</script>
|
|
</body>
|
|
</html> |