防抖源码及使用
<button class="btn">点击发送消息</button>
<!-- 防抖:就是要延迟执行,你一直操作触发事件一直不执行处理函数,只有当你停止操作等待多少秒后才执行 -->
<script>
function debounce(func, wait) {
let timer = null
return function(...args) {
if(timer) {
clearInterval(timer)
timer = null
}
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
function sendMessage(name) {
console.log(`${name}, i love you`)
}
const btn = document.querySelector('.btn')
const sendMsgDebounce = debounce(sendMessage, 3000)
btn.addEventListener('click', () => {
sendMsgDebounce('lisi')
})
节流源码及使用
方法一:时间戳
<button class="btn">点击发送消息</button>
<script>
function throttle(func, wait) {
let preTime = 0
return function(...args) {
if(new Date() - preTime > wait) {
func.apply(this, args)
preTime = new Date()
}
}
}
function sendMessage(name) {
console.log(`${name}, i love you`)
}
const btn = document.querySelector('.btn')
const sendMsgDebounce = throttle(sendMessage, 3000)
btn.addEventListener('click', () => {
sendMsgDebounce('lisi')
})
</script>
方法二:定时器
<button class="btn">点击发送消息</button>
<script>
function throttle(func, wait) {
let timer = null
return function(...args) {
if(!timer) {
timer = setTimeout(() => {
timer = null
func.apply(this, args)
}, wait)
}
}
}
function sendMessage(name) {
console.log(`${name}, i love you`)
}
const btn = document.querySelector('.btn')
const sendMsgDebounce = throttle(sendMessage, 3000)
btn.addEventListener('click', () => {
sendMsgDebounce('lisi')
})
</script>