I need a simple debounce function with immediate always true.
Without resorting to lodash and with the help of Can someone explain the "debounce" function in J
In essence, you need to share result of your debounce function. In your case, thats a promise:
const debouncedGetData = debounce(getData, 500)
let promiseCount = 0
let resultCount = 0
test()
function test() {
console.log('start')
callDebouncedThreeTimes()
setTimeout(callDebouncedThreeTimes, 200)
setTimeout(callDebouncedThreeTimes, 900)
}
function callDebouncedThreeTimes () {
for (let i=0; i<3; i++) {
debouncedGetData().then(r => {
console.log('Result count:', ++resultCount)
console.log('r', r)
})
}
}
function debounce(func, wait) {
let waiting;
let sharedResult;
return function() {
// first call will create the promise|value here
if (!waiting) {
setTimeout(clearWait, wait)
waiting = true
sharedResult = func.apply(this, arguments);
}
// else new calls within waitTime will be discarded but shared the result from first call
function clearWait() {
waiting = null
sharedResult = null
}
return sharedResult
};
}
function getData () {
console.log('Promise count:', ++promiseCount)
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(666)
}, 1000)
})
}