1、防抖
1.1 防抖的定义
当事件连续触发时,一段时间内没有再触发,就执行一次;如果这段时间内,又触发了,则重新计时。
1.2 使用场景
1.Input框的连续输入
2.登录、发短信等按钮避免用户点击太快,需要防抖。
3.频繁的滚动浏览器的滚动条,也需要用到防抖。
1.3 代码实现
function debounce(fn,delay = 500) {
let timer = null
return function() {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(fn,delay)
}
}
function scro() {
console.log('滚动了')
}
window.addEventListener('scroll',debounce(scro,500))
2、节流
2.1节流的定义
让高频事件触发,每隔n秒只执行一次。
2.2 使用场景
1.scroll事件,每隔n秒计算一次位置。
2.mousedown事件,每隔n秒触发一次。
3.鼠标的拖拽事件。
2.3 代码实现
<!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>
<style>
#demo {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div id="demo" draggable="true"></div>
</body>
</html>
let div = document.getElementById('demo')
function throttle(fn, delay = 100) {
let timer = null
return function() {
if (timer) {
return
}
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
}
function dragEvent(e) {
console.log(e.offsetX, e.offsetY)
}
div.addEventListener('drag', throttle(dragEvent, 500))