节流:在一定时间内只执行一次操作,不重复执行操作。
<!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>
<button id="btn">点击</button>
</body>
<script>
function thow(func, wait) {
let timer
return function () {
if (!timer) {
timer = setTimeout(() => {
func()
timer = null
}, wait)
}
}
}
function handle() {
console.log(Math.random())
}
document.getElementById('btn').onclick = thow(handle, 2000)
</script>
</html>
防抖:触发事件后,等待一定时间(如1000毫秒)再执行函数,如果在等待时间内又触发了事件,则重新计时。
<!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>
<input type="text" id="input" />
</body>
<script>
const input = document.getElementById('input')
function debounce(delay, calllback) {
let timer
return function (value) {
clearTimeout(timer)
timer = setTimeout(function () {
calllback(value)
}, delay)
}
}
function fn(value) {
console.log(value)
}
const debounces = debounce(1000, fn)
input.addEventListener('keyup', function (e) {
debounces(e.target.value)
})
</script>
</html>