简体   繁体   English

即使外部函数被多次触发,返回的内部函数如何引用相同的外部函数变量?

[英]How come returned inner functions reference the same outer function variable even when the outer function is fired multiple times?

I am trying to understand how this debounce function works:我试图了解这个去抖动功能是如何工作的:

const myInput = document.getElementById("myInput");

myInput.addEventListener(
    "keyup",
    debounce( helloWorld, 2000 )
);

function debounce( callback, delay ) {
    let timeout;
    return function() {
        clearTimeout( timeout );
        timeout = setTimeout( callback, delay );
    }
}

From my understanding, every time someone performs a "keyup" action, a new debounce function is fired and added to the call stack.据我了解,每次有人执行“keyup”操作时,都会触发一个新的 debounce 函数并将其添加到调用堆栈中。 Now it is my belief that each one of these debounce functions has its own independent notion of "timeout" which the inner function acts on.现在我相信这些去抖动函数中的每一个都有其内部函数作用的独立的“超时”概念。 However, the actual case it seems is that when "keyup" is performed many times, multiple inner functions are returned that all seem to share a reference to the same "timeout" variable, which allows this function to work.然而,实际情况似乎是,当多次执行“keyup”时,返回的多个内部函数似乎都共享对同一个“超时”变量的引用,这使得该函数可以工作。

My question is, where does my understanding fall apart?我的问题是,我的理解在哪里崩溃了? When "keyup" is fired multiple times, is it true that there are multiple debounce functions going to the call stack?当多次触发“keyup”时,是否有多个去抖动函数进入调用堆栈? Or is it just one function with one timeout variable, but with multiple returned functions?或者它只是一个具有一个超时变量的函数,但具有多个返回函数?

The debounce is called once. debounce被调用一次。 Then each time you release the key inner function is called.然后每次释放键时调用内部函数。

You can check this by adding a console.log inside the debounce您可以通过在debounce中添加一个console.log来检查这一点

The second argument that is passed to addEventListener is the inne function of the debounce传递给addEventListener的第二个参数是debounce的 inne 函数

Inner function is also created only once when you initialize the listener.初始化监听器时,内部函数也只创建一次。 This function is just called every time listener fires.每次侦听器触发时都会调用此函数。

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

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