Debounce function
JavaScript
Medium
Objective
Implement a debounce function in JavaScript
Requirements
Inside the
debouncefunction, write some logic to ensure thatfnis not called more than once within thedelaytimeThe debounced function should return immediately if its been less than
delaymilliseconds since the last time it was invokedIf the function is invoked during the delay period, it should wait a further
delaymilliseconds before executingfnYou can test your function by clicking the button and checking the console. The message should not appear more frequently that the
delaytimeYou 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