HTML事件处理程序,只传 delay,不使用 this
<body>
<input id="input" type="text" oninput="debounce_wrap(event)" />
<script>
function debounce(delay) {
let timer; // 定时器
return function (e) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
console.log(e.target.value);
}, delay);
}
}
let debounce_wrap = debounce(1000)
</script>
</body>
HTML事件处理程序,传 fn 和 delay
<body>
<input id="input" type="text" oninput="debounce_wrap(event)" />
<script>
function debounce(fn, delay) {
let timer; // 定时器
return function (e) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn(e);
}, delay);
}
}
//可以用箭头函数,因为我们不用 this
let debounce_wrap = debounce(e => console.log(e.target.value), 1000)
</script>
</body>
HTML事件处理程序,传 fn 和 delay,在html里需要绑定2次 this,因为HTML 事件处理程序会被注册到window上,如下所示,`debounce_wrap`是注册在window上的,需要用call重新绑定this,然后回调函数也要绑定一次 this
<body>
<input id="input" type="text" oninput="debounce_wrap.call(this)" />
<script>
function debounce(fn,delay) {
let timer; // 定时器
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.call(this); // 第二次绑定this html里的oninput里绑定第1次
}, delay);
}
}
//不要用箭头函数
let debounce_wrap = debounce(function(){console.log(this.value)},1000)
</script>
</body>
HTML事件处理程序,除了绑定 this,也可以直接将this作为参数传进去
<body>
<input id="input" type="text" oninput="debounce_wrap(this)" />
<script>
function debounce(param_this,fn,delay) {
let timer; // 定时器
return function (param_this) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.call(param_this); // 绑定传进来的this
}, delay);
}
}
//不要用箭头函数
let debounce_wrap = debounce(param_this=null,function(){console.log(this.value)},1000)
</script>
</body>
是不是觉得特别绕?
下面使用DOM2 事件处理程序,这个事件处理程序在元素的作用域中运行,只需要绑定一次this
<body>
<input id="input" type="text"/>
<script>
function debounce(fn,delay) {
let timer; // 定时器
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.call(this);
}, delay);
}
}
//不要用箭头函数
let debounce_wrap = debounce(function(){console.log(this.value)},1000)
document.getElementById('input').addEventListener('input',debounce_wrap)
</script>
</body>
DOM0事件处理程序也DOM2一样,事件处理程序在元素的作用域中运行,当前例子只需要绑定一次this,如下所示
<body>
<input id="input" type="text"/>
<script>
function debounce(fn,delay) {
let timer; // 定时器
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.call(this);
}, delay);
}
}
//不要用箭头函数
let debounce_wrap = debounce(function(){console.log(this.value)},1000)
document.getElementById('input').oninput=debounce_wrap
</script>
</body>
最后附一下节流函数的DOM0用法
<body>
<input id="input" type="text" />
<script>
function throttle(fn, delay) {
let timer; // 定时器
return function () {
if (!timer) {
timer = setTimeout(() => {
fn.call(this);
timer=null;
}, delay)
};
}
}
//不要用箭头函数
let debounce_wrap = throttle(function () { console.log(this.value) }, 1000)
document.getElementById('input').oninput = debounce_wrap
</script>
</body>