简体   繁体   English

Javascript 去抖 function 误解

[英]Javascript Debounce function misunderstand

In a course, the instructor wrote that debounce function:在一门课程中,导师写到去抖function:

const debounce = (func, delay) => {
    let timeId;
    return (...args) => {
        if(timeId) clearTimeout(timeId);
        timeId = setTimeout(() => {
            func.apply(null, args)
        }, delay)
    }
}

to use it in event listener like that像这样在事件监听器中使用它

input.addEventListener('input', debounce(onInput, 1000))

I think with every input we would reassign timeId to undefined which would make clearTimeout not working but it does work, How??我认为对于每个输入,我们都会将 timeId 重新分配给 undefined,这会使 clearTimeout 不起作用,但它确实有效,如何?

debounce() is only called once, when the event listener is added. debounce()仅在添加事件侦听器时调用一次。 It returns a closure that uses the same timeId variable every time it's called.它返回一个闭包,每次调用它时都使用相同的timeId变量。 So the variable isn't reset to undefined on every input.因此,变量不会在每个输入上重置为undefined

You would be correct if it were written like:如果它写成这样,你会是正确的:

input.addEventListener('input', function() { debounce(onInput, 1000); })

This would call debounce() on every input, which would create a new timeId variable.这将在每个输入上调用debounce() ,这将创建一个新的timeId变量。

Barmar's answer is correct but there is a simpler way of doing that using the bind function: Barmar 的回答是正确的,但是使用bind function 有一种更简单的方法:

input.addEventListener('input', debounce.bind(window, onInput, 1000))

The window at the start is the thisArg , the value of this in the function.开头的windowthisArgthis值在 function 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM