又是老生长谈的问题了,接下来我们就看一下具体的例子叭。
防抖
如果一直触发,则不执行。直到达到规定的时间,没有继续点击,就执行。
function debounce(fn, wait) {
let time = null;
return function (...args) {
// 每一次点击判断有延迟执行的任务就停止
time && clearTimeout(time);
//否则就开启延时任务
time = setTimeout(() => {
fn(...args)
}, wait);
}
}
应用示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="content"
style="height: 150px; line-height: 150px; text-align: center; color: #fff; background-color: #000; font-size: 100px;">
</div>
<script>
let num = 1;
const content = document.getElementById('content');
function count() {
content.innerText = num++
}
function debounce(fn, wait) {
let time = null;
return function (...args) {
// 每一次点击判断有延迟执行的任务就停止
time && clearTimeout(time);
//否则就开启延时任务
time = setTimeout(() => {
fn(...args)
}, wait);
}
}
content.addEventListener('mousemove', debounce(count, 300))
</script>
</body>
</html>
直到300ms内没有点击,数字才加一。
节流
频繁触发,只会在规定时间内执行一次。
//时间戳版本
function throttle(fn, wait) {
let pre = Date.now();
return function (...args) {
let now = Date.now();
if (now - pre > wait) {
pre = now;
console.log(pre);
fn(...args)
}
}
}
//定时器版本
function throttle(fn, wait) {
let time = null;
return function (...args) {
if (!time) {
time = setTimeout(() => {
// fn.apply(this, args);
fn(...args)
time = null
}, wait);
}
}
}
应用示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="content"
style="height: 150px; line-height: 150px; text-align: center; color: #fff; background-color: #000; font-size: 100px;">
1
</div>
<script>
let num = 1;
const content = document.getElementById('content');
function count() {
content.innerText = num++
}
function throttle(fn, wait) {
let time = null;
return function (...args) {
if (!time) {
time = setTimeout(() => {
fn(...args)
time = null
}, wait);
}
}
}
content.innerText = addEventListener('mousemove', throttle(count, 1000))
</script>
</body>
</html>
鼠标一直移动时,每一秒触发一次。