Debounce function with leading and trailing options | JavaScript Interview Question - 40

preview_player
Показать описание
JavaScript Interview Question - 40 | In this video, we will see how to solve a medium-difficulty problem asked in frontend engineer interview to SDE1, SDE2, and SDE3.

We will implement the classic debounce function in JavaScript as well as its variation that works with leading and trailing flags which are more often asked in frontend Interviews in Google, Uber, Atlassian, Flipkart, Cred, etc.

Loved the question? I have 120+ such solved problems in my ebook "JavaScript Interview Guide". If you are preparing for Interviews and looking for a solutions book, Get my Ebook.

Social links
Рекомендации по теме
Комментарии
Автор

Hi Prashant, solved it. I was confused at the start but your explanation helped. Thanks

//Below is my code
const debounce = (func, delay, {leading = false, trailing = false }) => {
let timeout = null
let isLeading = leading

return function(){
const context = this;
const args = arguments;

clearTimeout(timeout)

if(isLeading){
func.apply(context, args)
isLeading = false
}

timeout = setTimeout(() => {
if (trailing) {
func.apply(context, args);
}
if(leading){
isLeading = true
}
}, delay)
}
}

const onChange = (e) => {
console.log(e.target.value)
}

const debouncedSearch = debounce(onChange, 1000, { leading : true, trailing: true})

const input =
input.addEventListener('keyup', debouncedSearch)

akash-kumar
Автор

Hi Prasant, I think with trailing: true it works as throttling. Below is my solution. Thanks a lot for creating such videos. Really find it helpful.
export function debounceWithOptions(element) {
let timeout
let wait = false

const onChange = (e) => {
console.log(e.target.value)
}

const newDebounce = (
fn,
duration,
option = { leading: false, trailing: true }
) => {
return function (...args) {
if (option.leading) {
if (wait) {

}
fn(...args)
wait = true
setTimeout(() => {
= false
}, duration)
}
if (option.trailing) {
clearInterval(timeout)
timeout = setTimeout(() => {

}, duration)
}
}
}

const debouncedSearch = newDebounce(onChange, 1000, {
leading: true,
trailing: true
})

element.addEventListener('keyup', debouncedSearch)
}

jugalkumarseth
Автор

Nice bro waiting for more amazing content

soumakmaji
Автор

took some time to grasp it fully.

Why certain lines have been written the way they are.

PraveenKumar-wxyt
Автор

Please make a video in details on Promise Pool .

ujjawalkmr
visit shbcf.ru