2

Debounce using TDD

 11 months ago
source link: https://blog.navneet.dev/debounce-using-tdd/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
May 27, 2023 3 min read javascript

Debounce using TDD

Debounce using TDD

Photo by Samuel-Elias Nadler / Unsplash

Again, one of the frequently asked questions in Interviews.

Debouncing is a technique used in software development to limit the frequency of a function or event handler invocation. It ensures that a function is called only once after a certain delay, even if it is triggered multiple times within that delay period.

In other words, when debouncing a function, if the function is invoked multiple times within a specified time interval, only the last invocation will be executed after the delay has passed. The previous invocations are ignored or canceled.

debounce-4.gif

Debounce in action

Debouncing is commonly used in scenarios where you want to improve performance or avoid excessive executions of a function that can be triggered frequently, such as handling user input or event-based operations. By debouncing the function, you can control the rate at which it is called and optimize resource usage.

The typical flow of debouncing involves:

  1. When the debounced function is invoked, start a timer or clear the existing timer if it is already running.
  2. If the function is invoked again within the specified delay period, reset the timer.
  3. After the delay has passed and no additional invocations occur, execute the function.
Debouncing helps prevent unnecessary or rapid function invocations, especially in scenarios where the function's execution is resource-intensive or triggers expensive operations like network requests.

Common use cases for debouncing include:

  • Handling user input events like key presses, mouse movements, or scroll events to avoid excessive function calls while the user is still interacting.
  • Implementing search functionality where you wait for the user to finish typing before triggering a search API request.
  • Resizing event handlers to optimize performance when dealing with window resizing events.
debouncing.gif

Use case of debounce.(https://www.telerik.com/blogs/debouncing-and-throttling-in-javascript)

By applying debouncing, you can achieve better control over the timing and frequency of function invocations, leading to improved efficiency and a more responsive user experience.

Now we will go ahead and implement using TDD.

Setting up our environment.

mkdir debounce
cd debounce
npm init -y
npm install --save-dev jest

Setting up a new package 

Config package.json to run tests.

{
  "name": "debounce",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest test"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jest": "^29.5.0"
  }
}

Now let's write down the requirements in terms of tests.

  • Any debounced function should be called only after some defined delay.
  • Any debounced function should be called only once within the delay.
const debounce = require('./debounce');


test('debounced function should be called after delay', (done) => {
  const func = jest.fn(); //mocking a function
  const debouncedFunc = debounce(func, 200);

  debouncedFunc();
  expect(func).not.toBeCalled();

  setTimeout(() => {
    expect(func).toBeCalled();
    done();
  }, 300);
});

test('debounced function should be called only once within the delay', (done) => {
  const func = jest.fn();
  const debouncedFunc = debounce(func, 200);

  debouncedFunc();
  debouncedFunc();
  debouncedFunc();

  setTimeout(() => {
    expect(func).toBeCalledTimes(1);
    done();
  }, 300);
});

debounce.test.js

Now We will create the actual debounce.js and write minimal code.

function debounce(func, delay) {
  let timeoutId;

  return function () {
    clearTimeout(timeoutId);

    timeoutId = setTimeout(() => {
      func.apply(this, arguments);
    }, delay);
  };
}

module.exports = debounce;

debounce.js

The debounce function takes a function func and a delay delay as arguments. It returns a new debounced function that delays the execution func until the specified delay has passed. If the debounced function is invoked multiple times within the delay period, the previous timeout is cleared, and a new one is set.

Time for our tests.

npm test
Screenshot-2023-05-27-at-6.49.14-PM.png

Passing green tests.

Now, If I am an interviewer and I have to choose between a person with a fully tested code or one who is manually testing the code with `console.log` who do you think I will prefer.

Hope you liked the content. Reach out to me if you have doubts or just to say Hi. Feedbacks are always welcome and appreciated. Subscribe to this blog if you want to receive an update whenever I publish a new blog.

Find me @ Twitter / Portfolio


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK