{"resource":{"author":{"id":"3eh0kijZwMrHum8TkMqX","name":"Devtools Tech","username":"devtoolstech"},"content":{"link":"","difficulty":1,"domain":1,"type":1,"isInternal":true,"body":"Web performance is a key aspect and often discussed interview topic. All companies want their websites to load faster, stay performant, and provide smooth user experience.\r\n\r\nDebouncing is one of the techniques used to improve performance by limiting the frequency of a particular function being called, particularly in scenarios where the function is triggered frequently, such as input events like typing in an input field or scrolling. This ensures that the function is only called once after a specified period of inactivity.\r\n\r\n## Implementation\r\n\r\nWe can implement Debounce by creating a [Higher Order function](https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/) that will take the original function and a delay amount as input and returns a debounced version.\r\n\r\n```js\r\nfunction debounce(fn, delay) {\r\n  return function executedFunction() {\r\n    // some processing\r\n  }\r\n}\r\n```\r\n\r\nThe main behaviour of the debounce function is to defer the execution of the original function by the delay provided as the argument. We can do so by using the `setTimeout` method.\r\n\r\n```js\r\nfunction debounce(fn, delay) {\r\n  let timer;\r\n\r\n  return function executedFunction() {\r\n    timer = setTimeout(function() {\r\n      fn();\r\n    }, delay);\r\n  }\r\n}\r\n```\r\n\r\nThe idea is to call the original `fn` function if there is no user action for `delay` milliseconds. On every user action, the `executedFunction` would be called every timing. As per our current implementation, we are going to set a new timer that would result in `n` API calls. However, this is not the desired behaviour, we need to clear the old timer and set a timer on every user action.\r\n\r\n```js\r\nfunction debounce(fn, delay) {\r\n  let timer;\r\n\r\n  return function executedFunction() {\r\n    // clearing the current timer\r\n    clearTimeout(timer);\r\n\r\n    // settings a new timer\r\n    timer = setTimeout(function() {\r\n      fn();\r\n    }, delay);\r\n  }\r\n}\r\n```\r\n\r\nNow, we need to pass the arguments provided by the user to the original `fn` function.\r\n\r\n```js\r\nfunction debounce(fn, delay) {\r\n  let timer;\r\n\r\n  return function executedFunction() {\r\n    // arguments is an array-like object accessible inside a function\r\n    // it contains all the input arguments provided to the user\r\n    // we are converting it to an actual array using slice\r\n    const args = Array.prototype.slice.call(arguments);\r\n    // storing calling reference\r\n    const context = this;\r\n\r\n    // clearing the current timer\r\n    clearTimeout(timer);\r\n\r\n    // settings a new timer\r\n    timer = setTimeout(function() {\r\n      // invoking the fn with current context (this) and passing args\r\n      // apply method changes the context and takes arguments as an array\r\n      fn.apply(context, args);\r\n    }, delay);\r\n  }\r\n}\r\n```\r\n\r\nThis satisfies are all requirements. We are returning a debounced version of the original function that is invoked after every `n` milliseconds.\r\n\r\n## Examples\r\n\r\nOne example of debouncing is in handling search input on a website. Imagine a scenario where a user is typing in a search box to filter results. Without debouncing, a search API call would be triggered on every keystroke, leading to multiple unnecessary API calls. By implementing debouncing, we can delay the API call until the user stops typing for a specified amount of time, therefore reducing the number of API requests made and improving the overall performance of the search feature.\r\n\r\n```js\r\nfunction search(query) {\r\n  ...\r\n  // make API call here\r\n}\r\n\r\nconst debouncedSearch = debounce(search, 300);\r\n\r\n// debouncedSearch method either inside useEffect or onChange\r\n```\r\n\r\n## Practice\r\n\r\nThis concept is asked an interview questions of multiple companies like Flipkart, Visa, Amazon, and many more. You can try and see if you can pass all the test cases using the link below.\r\n\r\nhttps://devtools.tech/questions/s/implement-debounce-function-or-flipkart-ui-javascript-interview-questions---qid---CVSyd8uTdvVt1l2YcAcq","languages":[],"editorConfig":"undefined"},"stats":{"views":13086,"used":0,"likes":0},"description":"","published":true,"isActive":true,"tags":["javascript","frontend","ui","ux","devtools tech","coding","debounce","flipkart","react","tutorial","interviews","visa"],"slug":"what-is-debouncing-explain-with-examples---rid---bn9IQcem9rnLw7rT6gqk","isPremium":false,"categories":[],"requires":[],"_id":"662b53824079503047f86f7f","title":"What is Debouncing? Explain with examples","resourceId":"bn9IQcem9rnLw7rT6gqk","createdAt":1714115458275,"modifiedAt":1714115515970},"currentUser":null,"isOwner":false,"recommendations":{"questions":[{"_id":"61f82a28e12bce537863b05b","content":{"languages":["javascript","typescript"],"difficulty":4},"tags":["javascript","flipkart","debounce","web performance","programming","interview question","advanced js"],"slug":"implement-debounce-function-or-flipkart-ui-javascript-interview-questions---qid---CVSyd8uTdvVt1l2YcAcq","title":"Implement Debounce Function | Flipkart UI - JavaScript Interview Questions","questionId":"CVSyd8uTdvVt1l2YcAcq"},{"_id":"65ed848c4e1bed1edc06d1c4","content":{"languages":["react"],"difficulty":2},"tags":["javascript","frontend","ui","ux","code","machine coding round","razorpay","frontend interview question"],"slug":"how-to-build-a-pagination-component-in-react-js-or-razorpay-interview-question-or-javascript---qid---OZbNo0AUBGI97HX3gn3Z","title":"How to build a Pagination component in React.js? | Razorpay Interview Question | JavaScript","questionId":"OZbNo0AUBGI97HX3gn3Z"},{"_id":"64ecc241d5ab2876a4c336da","content":{"languages":["javascript","typescript"],"difficulty":1},"tags":["javascript","array","frontend","coding","interview","devtools tech","codedamn","frontend masters","interview question","lodash polyfill"],"slug":"implement-a-function-that-creates-an-array-of-values-not-included-in-other-array-or-lodash-difference-or-javascript-interview-question---qid---xjhgy8O1xkroU074X7EU","title":"Implement a function that creates an array of values not included in other array | Lodash Difference | JavaScript Interview Question  ","questionId":"xjhgy8O1xkroU074X7EU"},{"_id":"66de916920aedf09de82be99","content":{"languages":["javascript","typescript"],"difficulty":4},"tags":["javascript","interview questions","frontend problem solving","machine coding","awards","code","programming","tutorial","ui","ux","faang"],"slug":"how-to-implement-a-prize-calculator-javascript-interview-question---qid---0rDhVLnqTFqzycgfAGPq","title":"How to implement a prize calculator? JavaScript Interview Question","questionId":"0rDhVLnqTFqzycgfAGPq"},{"_id":"61f942d9e12bce537863b639","content":{"languages":["javascript","typescript"],"difficulty":2},"tags":["javascript","curry","frontend interview questions","walmart","flipkart","devtools","js fundamentals","currying"],"slug":"implement-currying-or-javascript-interview-questions---qid---YxO8Lh7qrIIRaSejXjBO","title":"Implement Currying | JavaScript Interview Questions","questionId":"YxO8Lh7qrIIRaSejXjBO"}],"resources":[{"_id":"69a7c86a92f33c7d8aa04cd9","content":{"difficulty":1,"domain":1,"type":2,"isInternal":false,"languages":[]},"tags":["javascript","ui","ux","devtools tech","coding","frontend","interview","growth","promotion"],"slug":"how-i-got-promoted-at-my-job---rid---mqhADdzPtZMdtHG2vbuU","title":"How I got promoted at my job?","resourceId":"mqhADdzPtZMdtHG2vbuU"},{"_id":"61f505741238c849f9e159e5","content":{"difficulty":4,"domain":2,"type":1,"isInternal":true},"tags":["javascript","pagination","remix run","frontend","tutorial","query params","navigation","js framework"],"slug":"add-pagination-to-remix-run---rid---A9jJkhqXgojvhovKZACe","title":"Add Pagination to Remix Run","resourceId":"A9jJkhqXgojvhovKZACe"},{"_id":"69a7c7b992f33c7d8aa04c41","content":{"difficulty":1,"domain":1,"type":2,"isInternal":false,"languages":[]},"tags":["javascript","ui","ux","devtools tech","coding","frontend","polyfill"],"slug":"implementing-javascript-promise-polyfill---rid---9ExnAPiGr8eioZLa9IeV","title":"Implementing JavaScript Promise Polyfill","resourceId":"9ExnAPiGr8eioZLa9IeV"},{"_id":"652501a4d5ab2876a4c96901","content":{"difficulty":1,"domain":1,"type":1,"isInternal":true,"languages":["javascript"]},"tags":["git","version control","beginner tip","devtools","frontend","coding","fullstack","backend","programing","bitbucket","github","gitlab","tutorial","tips","tricks"],"slug":"how-to-reset-a-single-file-from-the-feature-branch-to-the-remote-main-branch---rid---uCa6FoeftG05yLgJS8pD","title":"How to reset a single file from the feature branch to the remote main branch?","resourceId":"uCa6FoeftG05yLgJS8pD"},{"_id":"5f202d78cbec5f7ffc0c2fbd","content":{"difficulty":1,"domain":2,"type":2},"tags":["Lazy Loading"," Images"," React"," Intersection Observer"],"slug":"implementation-of-lazy-loading-image-oror-react-oror-intersection-observer---rid---iIx8G2ROXtX6ESYTpJ9a","title":"Implementation of Lazy Loading Image || React || Intersection Observer","resourceId":"iIx8G2ROXtX6ESYTpJ9a"}]}}