Search code examples
javascriptclosuresdebouncing

debounce closure shared by two functions


i am implementing debounce function. and i was able to successfully write the function then a confusing thought came to mind.

    function debounce(fn, timeout) {
        let timeoutRef;
        return function (...args) {
            const context = this;
            function cb() {
                fn.apply(context, args);
            }
            clearTimeout(timeoutRef);
            timeoutRef = setTimeout(cb, timeout);
        };
    }
    
    function foo() {
        console.log('foo is called');
    }
    function bar() {
        console.log('bar is called');
    }
    const debouncedFoo = debounce(foo, 10000);
    const debouncedBar = debounce(bar, 2000);
    
    debouncedFoo();  
    debouncedBar();

in the above code, don't debouncedFoo and debouncedBar share same colsure variable timeoutRef ?

if that's the case when debouncedFoo() it assigns setTimeout call reference to timeoutRef variable. And later when debouncedBar() called previous timeoutRef set by debouncedFoo() call should be be cleared and new setTimeout call reference should be assigned.

in conclusion,

expected result:

bar is called

actual result:

foo is called
bar is called 

can someone please help me understand this ?


Solution

  • in the above code, don't debouncedFoo and debouncedBar share same closure variable timeoutRef ?

    No they not sharing the same closure. in fact function parameters "fn" and "timeout" are also bounded in closure scope it means there are there parameter which is bounded in closure scope

    1. fn
    2. timeout
    3. timeoutRef

    and because you are calling debounce function 2 times so every caller have their own local stack and local closure. another thing which is important is clearTimeout(timeoutRef); here timeoutRef value is undefined so it will not work