(前端手撕) 9. 手写节流防抖
手写节流防抖
1. 节流
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>按钮</button>
<script>
// 节流: 在delay的时间内触发40次,也就执行1次
// 触发时,创建定时器,发现定时器存在就不继续向下执行,因此就保证了,在固定的时间间隔执行固定的次数
// 使用定时器和闭包实现
function throttle(fn, delay) {
var timer;
return function () {
if (timer) {
return;
}
timer = setTimeout(function () {
fn();
timer = null;
}, delay)
}
}
document.querySelector('button').onclick = throttle(function () {
console.log(1);
}, 1000)
// 时间戳实现节流函数:
// function throttle(fn, delay) {
// var previous = 0;
// // 使用闭包返回一个函数并且用到闭包函数外面的变量previous
// return function () {
// var now = new Date();
// if (now - previous > delay) {
// fn();
// previous = now;
// }
// }
// }
// document.querySelector('button').onclick = throttle(function () {
// console.log(1);
// }, 1000)
</script>
</body>
</html>
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
2. 防抖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>按钮</button>
<script>
// 防抖方法: 使用闭包,操作同一个timer:只有最后一次操作生效
// 触发时,创建定时器,当发现定时器存在就清除当前定时器,创建新的定时器
function debounce (fn,delay) {
var timer = null;
return function(){
if(timer){
clearTimeout(timer);
}
timer = setTimeout(function(){
fn()
},delay)
}
}
document.querySelector('button').onclick = debounce(function(){
console.log(1);
},2000)
</script>
</body>
</html>
查看1道真题和解析