javascript 函数节流 throttle 解决函数被频繁调用、浏览器卡顿的问题

时间:2023-03-09 01:47:32
javascript 函数节流 throttle 解决函数被频繁调用、浏览器卡顿的问题

* 使用setTimeout

index.html

<html>
<head>
<meta charset="UTF-8">
<title>throttle</title>
</head>
<body>
<h2>函数节流 解决函数被频繁调用、浏览器卡顿的问题</h2>
<script src="js/throttle.js"></script>
</body>
</html>

  

js/throttle.js

// 函数节流 解决函数被频繁调用、浏览器卡顿的问题
var throttle = function(fn, interval) {
var __self = fn, // 保存需要被延迟执行的函数引用
timer, // 定时器
firstTime = true; // 是否第1次被调用
return function() {
var args = arguments, __me = this; // 如果第1次被调用, 不需要延迟执行
if (firstTime) {
__self.apply(__me, args);
return firstTime = false;
}
// 如果定时器还在, 说明前一次延迟执行还没有完成
if (timer) {
return false;
}
// 延迟一段时间执行
timer = setTimeout(function() {
clearTimeout(timer);
timer = null;
__self.apply(__me, args);
}, interval || 500);
}
} var dom = document.createElement("h1");
dom.innerHTML = 0;
document.body.appendChild(dom); window.onresize = throttle(function() {
var n = parseInt(dom.innerHTML);
dom.innerHTML = ++n;
}, 500);

  

Run:

php -S 0.0.0.0:9000

调整浏览器窗口大小

javascript 函数节流 throttle 解决函数被频繁调用、浏览器卡顿的问题