How to use the debounce function from lodash

Find comprehensive JavaScript lodash.debounce code examples handpicked from public code repositorys.

In JavaScript, the _.debounce function in the Lodash library is used to limit the rate at which a function can be called.

6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
 *   'trailing': false
 * });
 *
 * // ensure `batchLog` is executed once after 1 second of debounced calls
 * var source = new EventSource('/stream');
 * source.addEventListener('message', _.debounce(batchLog, 250, {
 *   'maxWait': 1000
 * }, false);
 */
function debounce(func, wait, options) {
fork icon73
star icon711
watch icon29

+ 5 other calls in file

74
75
76
77
78
79
80
81
82
83
module.exports.curry3              = _.curry3;
module.exports.curryRight          = _.curryRight;
module.exports.curryRight2         = _.curryRight2;
module.exports.curryRight3         = _.curryRight3;
module.exports.cycle               = _.cycle;
module.exports.debounce            = _.debounce;
module.exports.deburr              = _.deburr;
module.exports.dec                 = _.dec;
module.exports.defaults            = _.defaults;
module.exports.defaultsDeep        = _.defaultsDeep;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.debounce work?

_.debounce is a function in the Lodash library for JavaScript that limits the rate at which a function can be called.

When _.debounce is called with a function as input, it performs the following operations:

  • It returns a new function that wraps the input function and limits the rate at which it can be called.
  • When the debounced function is called for the first time, it starts a timer that delays the execution of the input function by a specified amount of time.
  • If the debounced function is called again before the timer has expired, the timer is reset and the input function is delayed again.
  • If the debounced function is not called again before the timer expires, the input function is executed.
  • The debounced function returns the result of the last execution of the input function.

By using _.debounce, developers can limit the rate at which expensive or resource-intensive functions are called, which can improve performance and reduce the likelihood of errors. Note that _.debounce may not be suitable for all types of function calls, and the delay time should be carefully chosen to avoid unexpected behavior.

176
177
178
179
180
181
182
183
184
185

this.#pinger = setInterval(() => {
  this.ping();
}, ms('10 seconds'));

this.#recountGuests = debounce(() => {
  this.#recountGuestsInternal().catch((error) => {
    this.#logger.error({ err: error }, 'counting guests failed');
  });
}, ms('2 seconds'));
fork icon12
star icon30
watch icon5

1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
_initializerDefineProperty(_this, "previousEndpoint", _descriptor4, _assertThisInitialized(_this));

_initializerDefineProperty(_this, "previousSearchFilters", _descriptor5, _assertThisInitialized(_this));

_this.debouncedHandleSearch = void 0;
_this.debouncedHandleSearch = lodash.debounce(_this.handleSearch, props.debounceWait);

_this.updateValueCaches();

return _this;
fork icon3
star icon15
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const _ = require("lodash");

// Limiting the rate at which a function can be called
function expensiveFunction() {
  console.log("Expensive function called!");
}

const debouncedFunction = _.debounce(expensiveFunction, 1000);

debouncedFunction(); // Called immediately
debouncedFunction(); // Ignored
debouncedFunction(); // Ignored

// Wait for 1 second
// Outputs: "Expensive function called!"

In this example, we're using _.debounce to limit the rate at which the expensiveFunction is called. We provide the expensiveFunction as input to _.debounce, along with a delay time of 1000 milliseconds (1 second). The resulting debouncedFunction is then called three times in quick succession. Since the delay time has not elapsed, the first two calls to debouncedFunction are ignored. When the delay time expires, the third call to debouncedFunction triggers the execution of expensiveFunction, which outputs a message to the console. Note that in this example, we're passing the function directly to _.debounce, which returns a new function that limits the rate at which the input function can be called.

311
312
313
314
315
316
317
318
319
320
321
322
323
console.log(curry(1)(2)(3)); // => 6


const curryRight = _.curryRight((a, b, c) => a + b + c);
console.log(curryRight(3)(2)(1)); // => 6


const debounce = _.debounce(() => console.log('hello'), 100);
debounce();


const defer = _.defer(() => console.log('hello'));
defer();
fork icon0
star icon4
watch icon0

+ 15 other calls in file

11
12
13
14
15
16
17
18
19
20

useEffect(() => {
  if (typeof window !== 'undefined') {
    bodyRef.current = document.body
    const resizeObserver = new ResizeObserver(
      _.debounce(() => {
        setScrollVisible(bodyRef.current.scrollHeight > window.innerHeight * 1.1) //Visible if over 110vh
      }, 100)
    )
    resizeObserver.observe(bodyRef.current)
fork icon0
star icon2
watch icon1

+ 5 other calls in file

60
61
62
63
64
65
66
67
68
69
}

useEffect(() => {
  window.addEventListener('resize', _.debounce(resizeBox, 800))
  return () => {
    window.removeEventListener('resize', _.debounce(resizeBox, 800))
  }
}, [])

return (
fork icon0
star icon2
watch icon0

104
105
106
107
108
109
110
111
112
113
    /**
     * Delayed version of .start()
     *
     * @member {Function}
     */
    this._delayedStart = _.debounce(() => this._start(), UPSTREAM_START_DELAY);

}

// noinspection JSUnusedGlobalSymbols
fork icon0
star icon1
watch icon3

+ 5 other calls in file

9
10
11
12
13
14
15
16
17
18
19
20


module.exports = HttpProxyMiddleware


function HttpProxyMiddleware(context, opts) {
  // https://github.com/chimurai/http-proxy-middleware/issues/57
  var wsUpgradeDebounced = _.debounce(handleUpgrade)
  var wsInitialized = false
  var config = configFactory.createConfig(context, opts)
  var proxyOptions = config.options

fork icon0
star icon0
watch icon1

46
47
48
49
50
51
52
53
54
55
this.locationBar = new LocationBar();
this.openmct = openmct;
this.routes = [];
this.started = false;

this.setHash = _.debounce(this.setHash.bind(this), 300);

openmct.once('destroy', () => {
    this.destroy();
});
fork icon0
star icon0
watch icon274

+ 25 other calls in file

17
18
19
20
21
22
23
24
25
26
27
  } catch (err) {
    console.error("Error reading from db", err);
  }
});


const saveDb = _.debounce(
  async () => {
    try {
      const str = JSON.stringify(CACHE, null, __DEV__ ? 2 : undefined);
      await fs.promises.writeFile(PATH, str);
fork icon0
star icon0
watch icon1

+ 11 other calls in file

21
22
23
24
25
26
27
28
29
30
  this.emitter = new EventEmitter();

  this.emitter.on('train', this.on_train.bind(this));
  this.emitter.on(
    'train',
    _.debounce(this.recalculate_weights.bind(this), recalculation_time)
  );
}

on(event_name, cbk){
fork icon0
star icon0
watch icon1

+ 4 other calls in file

69
70
71
72
73
74
75
76
77
78
constructor(cy, view) {
  this.cy = cy;
  this.view = view;
  this.mouseoverEdgeIds = [];
  this.debouncedHighlight =
      _.debounce(this.setNewEdgeHighlight.bind(this), 10);
}

/**
 * Handles an event.
fork icon0
star icon0
watch icon1

+ 2 other calls in file

94
95
96
97
98
99
100
101
102
103
var _this = _super.call(this, props) || this;
_this.apolloLinks = {};
_this.observers = {};
_this.graphiqlComponents = [];
// debounce as we call this on each http header or endpoint edit
_this.getSchema = lodash_1.debounce(function (props) {
    if (props === void 0) { props = _this.props; }
    return __awaiter(_this, void 0, void 0, function () {
        var first;
        var _this = this;
fork icon0
star icon0
watch icon2

+ 2 other calls in file

6
7
8
9
10
11
12
13
14
15
16
17
18
var lodash_1 = require("lodash");


var deserialize_1 = require("./workspace/deserialize");


function serializeState(store) {
  return lodash_1.debounce(function () {
    var state = store.getState();


    if (!state.stateInjected) {
      localStorage.setItem('graphql-playground', JSON.stringify(state));
fork icon0
star icon0
watch icon2

+ 2 other calls in file

123
124
125
126
127
128
129
130
131
132
133
134
        $(element).autocomplete('search', '');
      }


      return true;
    };
    ko.utils.registerEventHandler(element, 'keyup', _.debounce(handleKeyEvent, 100));
  },
};


function WindowTitle() {
fork icon0
star icon0
watch icon0

102
103
104
105
106
107
108
109
110
111
112
113
console.log('curryRight4--->', curryRight4);
//curryRight4---> [ 1, 2, 3 ]


//_.debounce(func,[wait=0],[options={}])
// // Avoid costly calculations while the window size is in flux.
// jQuery(window).on('resize', _.debounce(calculateLayout, 150));


// // Invoke `sendMail` when clicked, debouncing subsequent calls.
// jQuery(element).on('click', _.debounce(sendMail, 300, {
//   'leading': true,
fork icon0
star icon0
watch icon0

+ 11 other calls in file

1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
  });
}

function setupSchemaRefresh(refresh) {
  const service = this;
  service.refreshSchema = _.debounce(updateSchema => {
    const params = {
      ...cnFlexFormConfig.getStateParams(service.getParamOverrides()),
      ...service.params
    };
fork icon0
star icon0
watch icon9

+ 5 other calls in file

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)