载流函数的使用

JavaScript节流函数(载流函数)Throttle解析

自己项目中一般载流函数的写法。

1
2
3
4
5
6
7
//截流函数
self.throttle = function (method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function () {
method.call(context);
}, 400);
};

载流函数的作用

在浏览器DOM事件中,有一些事件会随着用户的操作不间断的触发。

有时候如果事件处理方法比较庞大,DOM操作比较复杂,还不断的促发此类事件就会造成性能上的损失,导致用户体验较低(UI反应慢,浏览器卡死),所以通常我们会给相应事件添加延迟执行的逻辑。

网上copy的代码

1
2
3
4
5
6
7
var timer = null;
window.onresize = function () {
clearTimeout(timer);
timer = setTimeout(function() {
testFn();
}, 100);
};

感觉跟我项目用的差不多(我的书写主要是照着前一位学长写的)

产生的问题

如果js代码中还有别的功能也叫timer就产生冲突,可以采用闭包来解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var throttle = function (fn, delay) {
var timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(function() {
fn();
}, delay);
}
};
var f = throttle(testFn, 200);
window.onresize = function () {
f();
};