console
function debounce(fn, delay = 1000) {
let timer = null
return function(...args) {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
function throttle(fn, delay = 1000) {
let timer = null
let startTime = Date.now()
return function(...args) {
const currentTime = Date.now()
const remainingTime = delay - (currentTime - startTime)
clearTimeout(timer)
if (remainingTime < 0) {
fn.apply(this, args)
startTime = Date.now()
} else {
timer = setTimeout(() => {
fn.apply(this, args)
}, remainingTime)
}
}
}
function sayHi() {
console.log('debounce....')
}
const input = document.querySelector('#myinput')
input.addEventListener('input', throttle(sayHi, 2000))
<input id="myinput">