Advanced javascript functions to improve code quality (Part 1)

Glaston D'souza
5 min readMar 6, 2023

--

Introduction

Javascript is a beautiful programming language that can be used to write efficient, maintainable, and readable code.

In this blog post series, I’ll be covering a few built-in features that can be used to create some of the most powerful functions to boost your performance and make your code look much more beautiful.

Although the functions are explained using JavaScript, they could be easily implemented in any programming language. Once the concept of the different functions is understood, it can be applied everywhere.

Furthermore, the functions (or concepts) described in this post are often asked in technical interviews.

Whether you are a beginner or an experienced senior developer, these functions will optimize your code and coding experience. They will make working with JavaScript more enjoyable and efficient.

Debounce

What is debounce?

The term debounce comes from electronics. When you’re pressing a button, let’s say on your TV remote, the signal travels to the microchip of the remote so quickly that before you manage to release the button, it bounces, and the microchip registers your “click” multiple times.

To mitigate this, once a signal from the button is received, the microchip stops processing signals from the button for a few microseconds while it’s physically impossible for you to press it again.

Debounce in JavaScript

In JavaScript, the use case is similar. We want to trigger a function, but only once per use case.

Let’s say that we want to show suggestions for a search query, but only after a visitor has finished typing it.

This is a simple implementation of the debounce function

function debounce(func, timeout = 300){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}

// Any Function that you want to trigger.
function saveInput(){
console.log('Saving data');
}

const processChange = debounce(() => saveInput());

It can be used on an input:

<input type="text" onkeyup="processChange()" />

Or a window event:

window.addEventListener("scroll", processChange);

And on other elements like a simple JS function.

So what’s happening here? The debounce is a special function that handles two tasks:

  • Allocating a scope for the timer variable
  • Scheduling your function to be triggered at a specific time

Let’s explain how this works in the first use case with text input.

When a visitor writes the first letter and releases the key, the debounce first resets the timer with clearTimeout(timer). At this point, the step is not necessary as there is nothing scheduled yet. Then it schedules the provided function—saveInput()—to be invoked in 300 ms.

But let’s say that the visitor keeps writing, so each key release triggers the debounce again. Every invocation needs to reset the timer, or, in other words, cancel the previous plan withsaveInput(), and reschedule it for a new time—300 ms in the future. This goes on as long as the visitor keeps hitting the keys under 300 ms.

The last schedule won’t get cleared, so the saveInput() will finally be called.

Throttle

The Throttle function is similar to the Debounce function but with slightly different behavior. Instead of limiting the rate at which the function is called.

The Throttle function limits the rate at which the function is executed. This means it will forbid executing if the function was invoked before within a given period. It guarantees that a certain function runs at a consistent rate and won’t be triggered too often.

Why use Throttling in JavaScript?

Throttling functions generate function calls at a predetermined rate. Throttling the callbacks prevents the app from lagging or overloading your server with requests while performing a time-consuming computation or an API request in the event handler callback function.

The implementation of the Throttle function:

function throttle(cb, delay) {
let wait = false;

return (...args) => {
if (wait) {
return;
}

cb(...args);
wait = true;
setTimeout(() => {
wait = false;
}, delay);
}
}

In this snippet, the throttle function will execute a provided function func, update a wait variable to true, and then starts a timer which will reset the wait parameter after the delay is passed. If the throttle function is called again it will either call the provided function or simply return if the wait parameter is still true.

In the following snippet, you can see how the throttle function can be used:

// Define the function that updates the layout
function updateLayout() {
// Update the layout...
}

// Create a throttled version of the function
const throttledUpdateLayout = throttle(updateLayout, 250);

// Listen for window scroll events and call the throttled function
window.addEventListener("scroll", throttledUpdateLayout);

By defining the throttleUpdatedLayout function and specifying a delay of 250 milliseconds, it can be ensured that the updateLayout function will be executed at most once every 250 milliseconds when the window is scrolled. If the event is triggered before the delay is reached, nothing will happen.

Once

The Once function is a method that will prevent executing if already called. This is especially useful while working with event listeners, where you often encounter functions that only should run once. Instead of removing event listeners every time you can use the Once function in JavaScript.

The implementation of Once function:

function once(func) {
let ran = false;
let result;
return function() {
if (ran) return result;
result = func.apply(this, arguments);
ran = true;
return result;
};
}

For example, you can have a function that sends a request to a server to load some data. With the once() function, you could ensure that the request is not called multiple times if the user keeps clicking the button. This will avoid performance issues.

Without the once() function, you would remove the click listener instantly after the request is sent to prevent sending the request again.

Applying the once() function to any code will look like this:

// Define the function that sends the request
function requestSomeData() {
// Send the request...
}

// Create a version of the function that can only be called once
const sendRequestOnce = once(sendRequest);

// Listen for clicks on a button and call the "once" function
const button = document.querySelector("button");
button.addEventListener("click", sendRequestOnce);

In this example, the requestSomeData function will be called once, even if the user clicks the button multiple times.

Conclusion

This article covered concepts of Debounce, Throttle, and Once. Thank you for spending time reading it. I’ll be posting blogs covering more such advanced concepts. Stay tuned. ;)

--

--