{"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":14609,"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":"638b6012937c6f54916609f6","content":{"languages":["react"],"difficulty":2},"tags":["javascript","react","custom hook","interview","interview questions","devtools tech","questions","previous state","componentDidMount","shouldComponentUpdate"],"slug":"how-to-create-useprevious-hook-in-react-js-or-javascript-interview-question-or-frontend-problem-solving---qid---z4HmkKVlTn12wS5tOYLq","title":"How to create usePrevious hook in React.js? | JavaScript Interview Question | Frontend Problem Solving","questionId":"z4HmkKVlTn12wS5tOYLq"},{"_id":"697a002c132ce4e954c67f28","content":{"languages":["react"],"difficulty":2},"tags":["javascript","ui","ux","devtools tech","frontend interview question","hackerrank frontend interview question"],"slug":"spreadsheet-grid---qid---nBrwdTgAJo99lGIYefmC","title":"Spreadsheet Grid","questionId":"nBrwdTgAJo99lGIYefmC"},{"_id":"69c6c5807fa48f2af9fefb80","content":{"languages":["html"],"difficulty":1},"tags":["javascript","ui","ux","devtools tech","interview question","atlassian","frontend coding","ui challenges"],"slug":"real-time-comment-feed---qid---gxnubQDhcOkUH6VxaJra","title":"Real-Time Comment Feed","questionId":"gxnubQDhcOkUH6VxaJra"},{"_id":"5eb7d4a93f4a621665113a3c","content":{"difficulty":1,"languages":"css"},"tags":["html","css","frontend","css pseudo classes","css selectors","code"],"title":"Output question based on CSS Pseudo Classes","questionId":"ZUxQuaqGmB0JvxYz2jRK","slug":"output-question-based-on-css-pseudo-classes---qid---ZUxQuaqGmB0JvxYz2jRK"},{"_id":"6255a79c3ecc8e41a79f0c6a","content":{"languages":["javascript","typescript"],"difficulty":3},"tags":["javascript","classnames","package","polyfills","devtools","frontend","interview questions"],"slug":"implement-classnames-or-javascript-interview-question---qid---3QbZnesP6zJgC2jdLDjf","title":"Implement classNames() | JavaScript Interview Question","questionId":"3QbZnesP6zJgC2jdLDjf"}],"resources":[{"_id":"69b3e73392f33c7d8ab0e2bd","content":{"difficulty":4,"domain":2,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","ui","ux","devtools tech","interview experiences","frontend coding"],"slug":"cars24-frontend-interview-experience---rid---5CxS7tyPLqunm9n3xIfH","title":"Cars24 Frontend Interview Experience","resourceId":"5CxS7tyPLqunm9n3xIfH"},{"_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":"5f6994e06d3cda64e470c3f5","content":{"difficulty":2,"domain":2,"type":2,"isInternal":false},"tags":["javascript","reduce","array","polyfill","advanced javascript","interview question"],"slug":"implementation-of-reduce-polyfill-or-devtools-tech---rid---RPwJsAj15EZKfZsMT4V7","title":"Implementation of Reduce Polyfill | Devtools Tech","resourceId":"RPwJsAj15EZKfZsMT4V7"},{"_id":"692e9c62697e24762d339f5c","content":{"difficulty":1,"domain":2,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","ui","ux","devtools tech","tutorial","react","rendering","mount","lifecycle"],"slug":"re-rendering-vs-unmount-in-react---rid---JUT1eFkORr5oUDT2lXtc","title":"Re-rendering vs Unmount in React","resourceId":"JUT1eFkORr5oUDT2lXtc"},{"_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"}]}}