防抖和节流是针对响应跟不上触发频率这类问题的两种解决方法。防抖是给定一个周期延迟执行动作,若期间又被触发,则重新设定周期,直到周期结束,执行动作。
<style>
#content {
width: 150px;
line-height: 150px;
text-align: center;
color: #fff;
background-color: #ccc;
font-size: 80px;
}
</style>
</head>
<body>
<div id="content">1</div>
</body>
<script>
let num = 1;
let content = document.getElementById('content');
//计数函数
function count() {
content.innerHTML = num++;
};
function debounce(func, wait) {
let timer;
return function() {
let context = this; // 注意 this 指向
let args = arguments; // arguments中存着e
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
content.onmousemove = debounce(count, 1000);
节流的策略是,固定周期内,只执行一次动作,若在此周期内有新事件触发,不执行。周期结束后,又有事件触发,开始新的周期。
<style>
#content {
width: 150px;
line-height: 150px;
text-align: center;
color: #fff;
background-color: #ccc;
font-size: 80px;
}
</style>
</head>
<body>
<div id="content">1</div>
</body>
<script>
let num = 1;
let content = document.getElementById('content');
//计数函数
function count() {
content.innerHTML = num++;
};
// 定时器版
function throttle(fun, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
fun.apply(context, args)
}, wait)
}
}
}
//给content绑定鼠标移动事件
content.onmousemove = throttle(count, 3000);