throttle
function getUserAction(e) {
...
};
container.onmousemove = debounce(getUserAction, 1000);
- 第一版本,使用时间戳, 利用闭包保存previous的值,记录上一次运行的时间戳,与当前时间相差超过 wait 毫秒则运行
function throttle(func, wait) {
var context, args;
var previous = 0;
return function() {
var now = +new Date();
context = this;
args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}
- 第二版本,利用定时器,如果定时器存在,就不执行,直到定时器执行,然后执行函数,清空定时器,这样就可以设置下个定时器。
function throttle(func, wait) {
var timeout;
var previous = 0;
return function() {
context