debounce(防抖) 与 throttle(节流) 主要是用于用户交互处理过程中的性能优化。都是为了避免在短时间内重复触发(比如scrollTop等导致的回流、http请求等)导致的资源浪费问题。

debounce与throttle的区别主要在于:

1. debounce是通过设置定时器,在延迟的时间内每次触发都会重置定时器,直到在某个延迟时间点内不再触发事件才会执行。

2. throttle也是通过设置定时器,只是在延迟时间内用户只有首次触发是有效的,其他触发都是无效的,只有等延迟时间到了才会执行该事件。

理论有点枯燥,直接看代码:

 <!DOCTYPE html>
<html>
<head>
<title>debounce</title>
<style type="text/css">
#box {
width: 300px;
height: 150px;
border: 1px solid #eee;
background-color: #e3e3e3;
}
</style>
</head>
<body>
<div id="box"></div> <script type="text/javascript">
let divEle = document.querySelector('#box');
let count = 0;
divEle.addEventListener('mousemove', debounce(cbFn, 1000)); function debounce(callback, delay) {
let timer = null;
return function() {
timer && clearTimeout(timer);
timer = setTimeout(function(){
callback.apply();
}, delay)
}
} function cbFn() {
divEle.innerHTML = ++count;
}
</script>
</body>
</html>
 <!DOCTYPE html>
<html>
<head>
<title>throttle</title>
<style type="text/css">
#box {
width: 300px;
height: 150px;
border: 1px solid #eee;
background-color: #e3e3e3;
}
</style>
</head>
<body>
<div id="box"></div> <script type="text/javascript">
let divEle = document.querySelector('#box');
let count = 0;
divEle.addEventListener('mousemove', throttle(cbFn, 1000)); function throttle(callback, delay) {
let preTime = new Date().getTime();
return function() {
const now = new Date().getTime();
if (now - preTime > delay) {
preTime = now;
setTimeout(function() {
cbFn();
}, delay)
}
}
} function cbFn() {
divEle.innerHTML = ++count;
}
</script>
</body>
</html>
04-28 08:48