一、防抖
1.定义实现
当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
const debounce = (fn, wait) => {
let timer = null;
return (...args) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
};
2.测试代码:
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1" />
<title>debounce</title>
<style>
#container {
width: 100%;
height: 200px;
line-height: 200px;
text-align: center;
color: #fff;
background-color: #444;
font-size: 30px;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
const debounce = (fn, wait) => {
let timer = null;
return (...args) => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
};
var count = 1;
var container = document.getElementById("container");
function getUserAction(e) {
console.log(e);
container.innerHTML = count++;
}
container.onmousemove = debounce(getUserAction, 1000);
</script>
</body>
</html>
二、节流
1.定义实现
在规定时间内,保证执行一次该函数
const throttle = (fn, wait) => {
let last = 0;
return (...args) => {
let now = +new Date();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
};
// or
const throttle = (func, wait) => {
var timeout;
return (...args) => {
if (!timeout) {
timeout = setTimeout(function () {
timeout = null;
func.apply(this, args);
}, wait);
}
};
};
2.实现
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1" />
<title>throttle</title>
<style>
#container {
width: 100%;
height: 200px;
line-height: 200px;
text-align: center;
color: #fff;
background-color: #444;
font-size: 30px;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
const throttle = (fn, wait) => {
let last = 0;
return (...args) => {
let now = +new Date();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
};
var count = 1;
var container = document.getElementById("container");
function getUserAction(e) {
console.log(e);
container.innerHTML = count++;
}
container.onmousemove = debounce(getUserAction, 1000);
</script>
</body>
</html>