You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
861 B
35 lines
861 B
/** |
|
* 节流函数工具类 |
|
*/ |
|
define(function() { |
|
/** |
|
* 节流优化 |
|
* @param {Function} fun 回调函数 |
|
* @param {Number} delay 间隔时间 |
|
*/ |
|
function throttle(fun, delay) { |
|
var last = 0; // 最后调用的时间 |
|
var timer; // 最新一次的定时器 |
|
return function() { |
|
var main = this; // 获取方法对象 |
|
var params = arguments; // 方法参数 |
|
var now = +new Date(); // 最新调用的时间 |
|
if(now - last < delay) { |
|
// 在规定的间隔内,调用存为定时器,并清除上一次定时器调用 |
|
clearTimeout(timer); |
|
timer = setTimeout(function() { |
|
last = now; // 更新最后一次的调用时间 |
|
fun.apply(main, params); |
|
}, delay) |
|
} else { |
|
// 超过规定的间隔内,立即调用 |
|
last = now; |
|
fun.apply(main, params); |
|
} |
|
} |
|
} |
|
|
|
return { |
|
throttle: throttle |
|
} |
|
}) |