Throttling in JavaScript with TDD
source link: https://blog.navneet.dev/throttling-in-javascript-with-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.
Throttling in JavaScript with TDD
Photo by Moritz Mentges / Unsplash
Throttling is a mechanism that limits the number of times a function can be invoked within a specific time period. It guarantees that the function is called at a regular interval, regardless of how often it is triggered. Throttling helps prevent excessive function calls, which can lead to performance degradation or unnecessary resource consumption.
Throttling is particularly useful in scenarios where you want to limit the number of API requests or UI updates, optimizing performance and improving the overall user experience.
A component that is logging the number of clicks on every button click.
Example without throttling.
Without throttling - Image src
Example with throttling.
With throttling - Image src.
As you can see we are able to reduce the number of calls to function significantly. This will help in optimizing performance and improving the overall user experience.
In this blog post, we'll explore the concept of throttling in JavaScript, and implement it using Test-Driven Development (TDD) principles.
Implementing Throttling with Test-Driven Development (TDD)
Test-Driven Development (TDD) is an approach that advocates writing tests before writing the actual code. This technique ensures that your code is thoroughly tested, making it more robust and maintainable. Let's implement a throttling mechanism using TDD principles and see how it works.
Step 1: Set Up the Project
mkdir throttle
cd throttle
npm init -y
npm install --save-dev jest
Setting up a new package
Config package.json to run tests.
{
"name": "throttle",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest test"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^29.5.0"
}
}
Step 2: Write the Initial Test
Create a new file named throttle.test.js
and write the initial test case.
In this case, we'll create a test to verify that the throttled function is called only once within the specified time interval.
// throttle.test.js
const { throttle } = require('./throttle');
// We are using useFakeTimers method provided by JEST. This helps
// to test any method which may require waiting for some timeouts.
// Setting up timer
jest.useFakeTimers();
test('throttled function is called once within the specified time interval', () => {
const callback = jest.fn();
const throttledFn = throttle(callback, 1000);
throttledFn();
// Calling advanceTimerByTime(t) to advance the time by t milliseconds
jest.advanceTimersByTime(500);
throttledFn();
jest.advanceTimersByTime(500);
throttledFn();
expect(callback).toHaveBeenCalledTimes(2);
});
throttle.test.js
Step 3: Implement the Throttling Function
Create a new file named throttle.js
and implement the throttle
function based on the test case:
// throttle.js
function throttle(fn, delay) {
let run = false
return function (...args) {
if (!run) {
fn(...args)
run = true
setTimeout( () => run = false, delay)
}
}
}
module.exports = { throttle };
throttle.js
Step 4: Run the Test
Execute the following command to run the test:
$ npx test
If everything is set up correctly, you should see the test pass, indicating that the throttling mechanism works as expected.
Green tests.
Conclusion
Throttling is a valuable technique in JavaScript that allows you to control the rate at which a function is executed. In this blog post, we explored the concept of throttling and implemented it using Test-Driven Development (TDD) principles.
Remember, throttling is just one of the many techniques available to optimize your JavaScript code. Understanding when and how to use it can greatly enhance your application's performance and user experience. Happy throttling!
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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK