Finally dragged myself to continue blogging this morning. In this blog, I'll outline some useful Javascript snippets that prove useful on my journey to learning intermediate/advanced concepts.
debounce function
const debounce = (fn, delay = 300) => {
let timeoutId; // closure
return function(this, ...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), delay);
};
};
A debounce
function is used to limit the frequency of execution of another function, typically in response to an event (e.g. a button click, keypress, or resize event).
It ensures that the debounced function is executed only after a specified delay since the last time it was called. This is useful in scenarios where you want to prevent a function from being called too frequently, improving performance and reducing the risk of unintended multiple executions.
throttle function
const throttle = (fn, wait = 300) => {
let inThrottle, lastFn, lastTime; // closure
return function (this) {
const context = this, args = arguments;
if (!inThrottle) {
// 1st time -> set throttle flag
fn.apply(context, args);
lastTime = Date.now();
inThrottle = true;
} else {
// subsequent call -> clear timeout and set new if still within throttle period
clearTimeout(lastFn);
lastFn = setTimeout(() => {
if (Date.now() - lastTime >= wait) {
fn.apply(context, args);
lastTime = Date.now();
}
}, Math.max(wait - (Date.now() - lastTime), 0));
}
};
};
A throttle
function is a programming concept used to control the rate at which a function is called. It ensures that a function is not called more frequently than a specified time interval, even if it's triggered multiple times.
A throttle
function differs from the debounce
function because it calls the function first before preventing subsequent calls.
How the throttle function works:
- When the throttled function is called for the first time, it sets a timeout.
- If subsequent calls to the throttled function occur within the specified delay, they will be ignored.
- Once the delay has passed since the last invocation, the function will be called with the most recent arguments.
Event Emitter
class EventEmitter {
constructor() {
this.events = {};
}
subscribe(eventName, listener) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(listener);
}
unsubscribe(eventName, listener) {
if (this.events[eventName]) {
this.events[eventName] = this.events[eventName].filter(
(fn) => fn !== listener
);
}
}
// call the listeners subscribed to that event
emit(eventName, ...args) {
if (this.events[eventName]) {
this.events[eventName].forEach((listener) => {
listener(...args);
});
}
}
}
An event emitter is a fundamental design pattern in JavaScript that allows objects to subscribe to and listen for events, as well as emit events when certain actions occur.