In JavaScript interviews, another task comes up very often: write a debounce function. The task is usually described like this: “Write a function debounce that takes another function and a delay. It should return a new function that delays execution until the user stops triggering it for a certain amount of time.” In practice, this is used for things like search inputs — where calling a function on every keystroke would be inefficient. The main idea is simple: cancel the previous timer, start a new one, and execute the function only after the delay passes. I’ve added a short example on the screenshot that shows how this works in real code. If you understand debounce, you already understand an important part of performance optimization in frontend. Have you had this task in interviews too? #javascript #frontend #webdevelopment #interview #codinginterview #react #programming #softwareengineering
What about context binding???
Это очень важная функция особенно при отправке запросов на сервер, всяких events которые могут вызываться каждую секунду по 5 10 раз, но я так же хотел бы добавить от себя что тут еще если добавить throttle функцию то тогда вообще все встает на свои места. Обычно я в своих проектах прописываю и throttle и debounce сразу в utils, потому что точно уверен что они сыграют очень важнейшую роль. Но я бы от себя добавил бы сюда условие на проверку существующего id то есть if (timerId) clearTimeout(timerId)
This is non-sence
I had this question once
Thanks for sharing!
Arrow functions do not fix all the this keyword problem, this code above is prime example of that , this inside the returned arrow function would either be (window (non-strict mode) or undefined (strict mode) ,because arrow function get their this from enclosing scope , in case you assign a debounced function to an object obj.method = debounce(obj.method, 200); obj.method(); and if the method has this keyword in it , it will break , but the fix is easy too convert the wrapper to normal function to get dynamic this and replace fn(..args) with fn.call or fn.apply - that will be a decent attempt for an interview answer