Debouncing in JavaScript

DEFINATION

By Javascript

The concept of debouncing is pretty straightforward. It delays the function invocation by a defined period of time to avoid unnecessary invocations. So, the function will only be invoked if no event is triggered within that time, If the user triggers a new event during that time the time will be reset.

By Me

Dekho har bar event par function call karne ki bajaye ek time set kr diya jaata hai jisase pata chale ki user abb output chahata hai or time khatam hone par function call ho jata hai. Agar hum 5 bar ki jagah ek bar function call karainge to application ki speed badhegi obevious hai.

Example 1

In This example when you stop writing for 2 second alert will be showing = "Function run after 2 seconds"

1const Example1 = () => {
2  const debounceFun = (fun, delay) => {
3    var timer;
4
5    return function () {
6      clearTimeout(timer);
7      timer = setTimeout(() => {
8        fun();
9      }, delay);
10    };
11  };
12
13  const innerFun = debounceFun(() => {
14    alert("Function run after 2 second");
15  }, 2000);
16  return (
17    <input
18      onChange={innerFun}
19      type="text"
20      name=""
21      id=""
22    />
23  );
24};
Namaste