<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">点击</button>
<br />
<br />
<br />
<br />
<br />
参考文档:https://www.bilibili.com/video/BV1vo4y1y7tD?p=16
<script>
const { log } = console
var btn = document.getElementById('btn')
function myDebounce(fn, wait, immediate) {
if (typeof fn === 'function') throw new Error('fn is not an function')
if (typeof wait === 'undefined') wait = 300
if (typeof wait === 'boolean') {
immediate = wait
wait = 300
}
if (typeof immediate === 'undefined') immediate = false
let timer = null
return function (...args) {
let self = this,
init = immediate && !timer
clearTimeout(timer)
log('timer', timer, init)
timer = setTimeout(() => {
log('timer2', timer, init)
log('执行了')
timer = null
!immediate ? fn.apply(this, args) : null
}, wait)
init ? fn.apply(this, args) : null
}
}
function btnClick(ev) {
log('点击了', this, ev)
}
btn.onclick = myDebounce(btnClick, 1000, false)
</script>
</body>
</html>