Debounce function
JavaScript
Medium
Objective
Implement a debounce function in JavaScript
Requirements
Inside the
debounce
function, write some logic to ensure thatfn
is not called more than once within thedelay
timeThe debounced function should return immediately if its been less than
delay
milliseconds since the last time it was invokedIf the function is invoked during the delay period, it should wait a further
delay
milliseconds before executingfn
You can test your function by clicking the button and checking the console. The message should not appear more frequently that the
delay
timeYou should not use any external libraries or frameworks
Starting code
function debounce(fn, delay) {
// Your code here
}
function testFunction() {
const date = new Date();
console.log(`Button clicked at ${date.getSeconds()}s and ${date.getMilliseconds()}ms`);
}
function createButton() {
const button = document.createElement('button');
button.id = 'clickMe';
button.innerHTML = 'Click Me';
document.body.appendChild(button);
button.addEventListener('click', debounce(testFunction, 300));
}
document.addEventListener("DOMContentLoaded", function() {
createButton();
});
Check your solution
Tests
Function name is debounce | |||
debounce("fn",300) | Expected: | "call the function once if called multiple times quickly" | |
debounce("fn",350) | Expected: | "should call the function again if called after the delay period" |
Solution
Here's how I would approach this, but keep in mind there might be other ways to solve this problem.
function debounce(fn, delay) {
let timer = null;
return function() {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
}
}
Click to reveal