Lodash _.once() Method
Last Updated :
03 Nov, 2023
Lodash _.once() method of Function in lodash is used to create a function that calls the func parameter of this method only once. However, repeated calls to this function will return the value returned in the first call.
Note:
The function parameter of this method is called with this binding along with the arguments of the created function.
Syntax:
_.once(func);
Parameters:
This method accepts a single parameter which is described below:
- func: It is the function that is to be restricted.
Return Value:
This method returns the new restricted function.
Example 1: In this example, the hold is called multiple times but only the value of the first call is returned as you can call func only once as stated above.
Javascript
const _ = require( 'lodash' );
let hold = _.once( function (trap) {
console.log(trap + '!' );
});
hold( 'Logged in to the console' );
hold( 'GfG' );
hold( 'CS' );
|
Output:
Logged in to the console!
Example 2: In this example, each time the fetch is called the same value is returned as returned to the first call.
Javascript
const _ = require( 'lodash' );
let fetch = _.once( function (value) {
return value;
});
console.log(fetch(1013));
console.log(fetch(1014));
|
Output:
1013
1013
Reference: https://lodash.com/docs/4.17.15#once
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...