I am trying to construct a debounce function definition to give following results. My following code prints the following.
'hi'
'hi'
'hi'
'hi'
I am struggling to figure out how I can leverage interval
to contain x
as undefined
and once this expires again the function returns 'hi'
function debounce(callback, interval) {
return () =>{
let x = callback();
setTimeout(()=>{
x = callback();
},interval);
return x;
}
}
// Expectation running below statements
function giveHi() { return 'hi'; }
const giveHiSometimes = debounce(giveHi, 3000);
console.log(giveHiSometimes()); // -> 'hi'
setTimeout(function() { console.log(giveHiSometimes()); }, 2000); // -> undefined
setTimeout(function() { console.log(giveHiSometimes()); }, 4000); // -> undefined
setTimeout(function() { console.log(giveHiSometimes()); }, 8000); // -> 'hi'