Debounce function

JavaScript
Medium

Objective

Implement a debounce function in JavaScript

Requirements

  1. Inside the debounce function, write some logic to ensure that fn is not called more than once within the delay time

  2. The debounced function should return immediately if its been less than delay milliseconds since the last time it was invoked

  3. If the function is invoked during the delay period, it should wait a further delay milliseconds before executing fn

  4. You can test your function by clicking the button and checking the console. The message should not appear more frequently that the delay time

  5. You 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