<input type="text" id="inputField">
const inputField = document.querySelector('#inputField')
inputField.addEventListener('input', debounce(
function(e){
const userInputValue = e.target.value
console.log(userInputValue)
},
1000,
true
))
function debounce(callback, wait, immediate) {
let timeout = null
function wrapper(args) {
// 保留回傳 function 中的 this 狀態
const self = this
// 將一個待執行的函式存於 later 中
// wrapper 的 timeout 值會在你設定的時間內,隨著你敲擊鍵盤時
// 不斷地被執行 clearTimeout 和 setTimeout 的過程
// 所以永遠只會保留一個
const later = () => {
timeout = null
if (!immediate) callback.apply(self, args)
}
const callNow = immediate && !timeout
clearTimeout(timeout);
timeout = setTimeout(later, wait);
// 如果你設定了 immediate,雖說隨著你的鍵盤敲擊,過往的 timeoutId 也會被洗掉,但由於有 !immediate 為 false 的關係,所以 later 並不會執行你所設定的函式
if (callNow) callback.apply(this, args);
}
return wrapper;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.