debounce防抖
function getUserAction(e) {
...
};
container.onmousemove = debounce(getUserAction, 1000);
最简单版本,利用setTimeout 和 clearTimeout
function debounce(func, wait) {
var timeout;
return function () {
clearTimeout(timeout)
timeout = setTimeout(func, wait);
}
}
- debounce 函数的 return function 内部的 this 会指向调用函数的this
修改this,使其不受调用函数的影响
function debounce(func, wait) {
var timeout;
return function () {
var context = this;
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context)
}, wait);
}
}
或者 使用箭头函数
function debounce(func, wait) {