在前端开发中有一部分用户的行为会频繁的触发时间执行,而对于dom操作、资源加载等耗费性能的处理,很有可能导致界面卡顿,甚至浏览器的崩溃。
函数节流就是预定一个函数只有在大于执行周期时才执行,周期内调用不执行。好像水滴积攒到一定程度才会触发一次下落一样。
应用场景;
- 抢购疯狂点击
- 窗口调整
- 页面滚动
实现代码:
/**
* 节流, 让每隔wait毫秒才执行一次handler函数
*/
function throttle(handler, wait){
wait = wait || 1000; //不传默认是一秒钟
var lastTime = 0;
return function(){
var nowTime = new Date().getTime();
if(nowTime - lastTime > wait){
handler();
lastTime = nowTime;
}
}
}
测试用例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<div id="show">0</div>
<button id="btn">
click
</button>
<script type="text/javascript">
/**
* 节流, 让每隔wait毫秒才执行一次handler函数
*/
function throttle(handler, wait){
wait = wait || 1000; //不传默认是一秒钟
var lastTime = 0;
return function(){
var nowTime = new Date().getTime();
if(nowTime - lastTime > wait){
handler();
lastTime = nowTime;
}
}
}
var oDiv = document.getElementById('show')
var oBtn = document.getElementById('btn');
function add() {
oDiv.innerText = parseInt(oDiv.innerText) + 1;
}
// var newAdd = throttle(add)
oBtn.onclick = throttle(add);
</script>
</body>
</html>