Kraken
Kraken

Reputation: 1955

Debounce function meaningless line

I have a debounce function taken from web.

function debounce(f, ms) {
    let timer = null;

    return function(...args) {
        const onComplete = () => {
            f.apply(this, args);
            timer = null;
        }

        if (timer) {
            clearTimeout(timer);
        }

        timer = setTimeout(onComplete, ms);
    }   

}

Why exactly do we need this line f.aply(this, args), if we can just change this line to f(args) and result will be same.

Upvotes: 1

Views: 78

Answers (1)

georg
georg

Reputation: 214949

If you invoke your debounced function without this:

let deb = debounce(...);
deb()

there's no difference.

If you invoke it with this (via bind/call/apply), you do need the apply line to pass this correctly to the source function:

"use strict";

function debounce(f, ms) {
    let timer = null;

    return function(...args) {
        const onComplete = () => {
            console.log('with apply:')
            f.apply(this, args);
            console.log('without apply:')
            f(...args)
            timer = null;
        }

        if (timer) {
            clearTimeout(timer);
        }

        timer = setTimeout(onComplete, ms);
    }   

}

let x = {y: 1};
let deb = debounce(function() { console.log(this)}, 3);
deb.apply(x)

Upvotes: 1

Related Questions