{"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":12543,"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":"6278dce36865f21215beeece","content":{"languages":["react","html"],"difficulty":1},"tags":["javascript","react","begineer","ui","forntend challenge","coding problems","problem solving","mockups","ux","interview","frontend coding challenges","codedamn","frontend masters"],"slug":"how-to-build-a-text-converter-or-frontend-coding-challenge-or-react-js-or-beginner---qid---OX4jbE2JFb2DS5mO8Vu7","title":"How to build a Text Converter? | Frontend Coding Challenge | React.js | Beginner","questionId":"OX4jbE2JFb2DS5mO8Vu7"},{"_id":"645b815c6577005718bc9ed7","content":{"languages":["javascript","typescript"],"difficulty":1},"tags":["frontend","code","programming","lodash","polyfill","lodash once","javascript interview question","ui","ux","devtools tech","codedamn","egghead","frontend masters","problem solving","frontend interview questions","underscore","geeksforgeeks"],"slug":"implement-a-function-that-accepts-a-callback-and-restricts-its-invocation-to-at-most-once-or-lodash-polyfills-or-frontend-problem-solving---qid---RLIaoJTXeiN81W2HQYry","title":"Implement a function that accepts a callback and restricts its invocation to at most once | Lodash Polyfills | Frontend Problem Solving","questionId":"RLIaoJTXeiN81W2HQYry"},{"_id":"5e9c68f1982bd3483e04bcc8","content":{"languages":["javascript"],"difficulty":1},"tags":["node.js","promises","react.js","javascript","frontend","programming","code","interview","frontend fundamentals"],"title":"What would be the output of the following code snippet? | Promise Based Output Question | Part One","questionId":"TQBJFJPPHX4VxH0MrxBt","slug":"what-would-be-the-output-of-the-following-code-snippet-or-promise-based-output-question-or-part-one---qid---TQBJFJPPHX4VxH0MrxBt"},{"_id":"698cd2ea895fc3bf0142a54f","content":{"languages":["javascript","typescript"],"difficulty":2},"tags":["javascript","ui","ux","devtools tech","questions","frontend interview","google"],"slug":"priority-based-data-fetching---qid---VpqJajJMcGBmxW556YM4","title":"Priority Based Data Fetching","questionId":"VpqJajJMcGBmxW556YM4"},{"_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":"5fc7215a6d3cda64e470c415","content":{"difficulty":4,"domain":1,"type":5},"tags":["linkedin","jobs","skills","career","indemand","devtools"],"slug":"move-close-to-your-dream-job-find-out-top-skills-in-the-market---rid---layhD7GHUKsulhIM25yM","title":"Move close to your dream job. Find out top skills in the market.","resourceId":"layhD7GHUKsulhIM25yM"},{"_id":"692995368f12450e2fdcb3f8","content":{"difficulty":4,"domain":1,"type":2,"isInternal":false,"languages":[]},"tags":["javascript","ux","ui","promise","tutorial","video","coding","frontend","async programming","frontend development"],"slug":"how-to-solve-promise-based-javascript-output-questions-or-ultimate-trick---rid---nJFmM6cYVm05Lfjuh4t0","title":"How to solve Promise Based JavaScript Output Questions? | Ultimate Trick!","resourceId":"nJFmM6cYVm05Lfjuh4t0"},{"_id":"69036a803177c39e85554ace","content":{"difficulty":1,"domain":2,"type":1,"isInternal":true,"languages":[]},"tags":["javascript","frontend","ui","ux","uber","senior frontend engineer"],"slug":"uber-senior-frontend-interview-experience---rid---HhAZPA5jvh67sTfzr8cw","title":"Uber Senior Frontend Interview Experience","resourceId":"HhAZPA5jvh67sTfzr8cw"},{"_id":"63f077e9412456738aaee88c","content":{"difficulty":1,"domain":2,"type":1,"isInternal":true,"languages":["react"]},"tags":["javascript","frontend","code","programming","ui","ux","interactive examples","codedamn","nth-child selectors","pseudo selectors","css selectors","sass","scss","less","styling","html","css fundamentals","frontend fundamentals","examples","codesandbox"],"slug":"understanding-nth-child-selectors-in-css---rid---ZD7WRQQ8iSNv8SCSZdTG","title":"Understanding Nth-Child Selectors in CSS","resourceId":"ZD7WRQQ8iSNv8SCSZdTG"},{"_id":"66a4ca5daac82a58634c2bfe","content":{"difficulty":4,"domain":2,"type":1,"isInternal":true,"languages":["undefined"]},"tags":["javascript","frontend","ui","ux","coding","atlassian","frontend coding challenge","feature flags","interactive shape"],"slug":"top-atlassian-frontend-interview-questions-and-process---rid---Bu7bJx9jNVoIsrH71Byb","title":"Top Atlassian Frontend Interview Questions and Process","resourceId":"Bu7bJx9jNVoIsrH71Byb"}]}}