Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax:
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Single Initialization Function:
4.2.
JavaScript
4.3.
One-Time Event Handler:
4.4.
JavaScript
4.5.
Single Execution in Asynchronous Operations:
4.6.
JavaScript
4.7.
Preventing Duplicate Submissions:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
Can _.once() be reset to allow the function to run again?
5.2.
Does _.once() affect the original function?
5.3.
Is _.once() suitable for functions with side effects?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.once() Method

Author Riya Singh
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In certain scenarios, ensuring that a function is executed only once, regardless of how many times it's called, is crucial for controlling side effects, managing resource usage, or handling initialization routines. Lodash provides a helpful utility for this purpose: the _.once() method. This function creates a version of the provided function that can only be called once. Subsequent calls return the result of the first call, ensuring that the function's logic is executed only a single time. 

Lodash _.once() Method

This article will delve into the _.once() method, discussing its syntax, applications, and utility, illustrated through examples and FAQs.

Why This Function is Used

The _.once() function is used to restrict a function to a single execution. This is especially useful for initialization routines that must run only once, event handlers that should execute just one time in response to an event, or any function where repeated execution could lead to errors, unnecessary computations, or undesired side effects.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax:

_.once(func)

Parameters:

func (Function): The function to restrict to a single call.

Return Value: 

(Function) - Returns the new restricted function.

Examples 

Single Initialization Function:

  • JavaScript

JavaScript

var _ = require('lodash');

function initialize() {

 console.log('Initialization completed');

}

var initializeOnce = _.once(initialize);

initializeOnce(); // Output: 'Initialization completed'

initializeOnce(); // No output on subsequent calls


Demonstrates ensuring an initialization function is only executed once.

One-Time Event Handler:

  • JavaScript

JavaScript

var button = document.getElementById('myButton');

var handleClickOnce = _.once(() => console.log('Button clicked'));

button.addEventListener('click', handleClickOnce);


// 'Button clicked' is logged only on the first click

Shows using _.once() for an event handler to respond to the first event only.

Single Execution in Asynchronous Operations:

  • JavaScript

JavaScript

function fetchData(callback) {

 // Simulate fetching data

 setTimeout(callback, 1000);

}

var logDataOnce = _.once(() => console.log('Data fetched'));

fetchData(logDataOnce);

fetchData(logDataOnce);

// 'Data fetched' is logged only once, even though fetchData is called twice

An example of using _.once() in asynchronous operations to avoid duplicate actions.

Preventing Duplicate Submissions:

  • JavaScript

JavaScript

function submitForm() {

 console.log('Form submitted');

}

var submitFormOnce = _.once(submitForm);

submitFormOnce();

submitFormOnce(); // Subsequent calls do nothing

Output: 

'Form submitted'


Demonstrates using _.once() to prevent duplicate form submissions.

Frequently Asked Questions 

Can _.once() be reset to allow the function to run again?

No, once _.once() is applied to a function, it cannot be reset. The function will always return the result of the first call.

Does _.once() affect the original function?

No, _.once() does not alter the original function. It creates a new function with the once-only restriction.

Is _.once() suitable for functions with side effects?

Yes, _.once() is particularly suitable for functions with side effects that should only occur once, like initialization routines or API calls.

Conclusion

Lodash's _.once() method is a simple yet powerful tool for ensuring that a function is executed only a single time. It's especially useful for managing one-time operations, initialization tasks, and preventing duplicate actions in event-driven programming.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.overArgs() Method
Next article
Lodash _.isArrayLike() Method
Live masterclass