防抖示例函数展开赋值的写法有误
LegendLeo opened this issue · 2 comments
LegendLeo commented
防抖
这个示例的展开赋值...arg写错了地方,写到里面的话,arg取得的值是 event
应该写到外层的参数中,如下
const debonce = (func, wait = 100, ...args) => {
let timer = null
return function () {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}这样才取得到
我的demo如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Debonce</title>
</head>
<body>
<input type="button" value="1">
<script>
let btn = document.querySelector('input')
function add(step = 1) {
btn.value = parseInt(btn.value) + step
}
const debonce = (func, wait = 100, ...args) => {
let timer = null
return function () {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
btn.addEventListener('click', debonce(add, 800, 3))
</script>
</body>
</html>zvzuola commented
@LegendLeo 原来的写法是对的,你想象一下假如不考虑debonce,你直接btn.addEventListener('click', add),这个时候add的接受的参数也是event。你的需求应该是下面的写法:
<script>
let btn = document.querySelector('input')
function add(step = 1) {
btn.value = parseInt(btn.value) + step
}
function onClick(e) {
add(3)
}
const debonce = (func, wait = 100) => {
let timer = null
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
btn.addEventListener('click', debonce(onClick, 800))
</script>