引言
网上有不少防抖代码是内含传参功能的,但是没有具体的传参使用实例,希望我的案例能帮到大家。
实例:输入同时显示,防抖延迟显示
无传参版
HTML
<div>
<input id="input" type="text">
<p id="content"></p>
</div>
JS
let input = document.getElementById('input');
let content = document.getElementById('content');
input.onkeyup=debounce(show,1000);
function show() {
content.innerHTML+=this.value+'<br/>';
}
function debounce(func,delay) {
let timer;
return function () {
if(timer)
clearTimeout(timer);
timer= setTimeout(()=>{
func.call(this);
},delay);
}
}
传参版
let input = document.getElementById('input');
let content = document.getElementById('content');
//将this绑定到input上,并传递参数
input.onkeyup=debounce(show,1000).bind(input,',hello',',world');
function show(arg1,arg2) {
content.innerHTML+=this.value+arg1+arg2+'<br/>';
}
function debounce(func,delay) {
let timer;
return function () {
if(timer)
clearTimeout(timer);
timer= setTimeout(()=>{
func.call(this,...arguments);
},delay);
}
}
注意坑(下面写法都无效)!!!
//无效,onkeyup需要赋值一个函数,而该写法为立即执行。
input.onkeyup=debounce(show,1000)(',hello',',world');
//无效,会丢失指向input的this,show函数内获取不到input的值。
input.onkeyup=function() {
debounce(show, 1000)(',hello',',world');
}