Can someone explain the “debounce” function in Javascript

后端 未结 8 830
旧时难觅i
旧时难觅i 2020-11-22 02:57

I am interested in the \"debouncing\" function in javascript, written here : http://davidwalsh.name/javascript-debounce-function

Unfortunately the code is not explai

8条回答
  •  你的背包
    2020-11-22 03:25

    What you want to do is the following: If you try to call a function right after another, the first should be cancelled and the new one should wait for a given timeout and then execute. So in effect you need some way of cancelling the timeout of the first function? But how? You could call the function, and pass the returning timeout-id and then pass that ID into any new functions. But the solution above is way more elegant.

    What it does is effectively make the timeout variable available in the scope of returned function. So when a 'resize' event is fired it does not call debounce() again, hence the timeout content is not changed (!) and still available for the "next function call".

    The key thing here is basically that we call the internal function every time we have a resize event. Perhaps it is more clear if we imagine all resize-events is in an array:

    var events = ['resize', 'resize', 'resize'];
    var timeout = null;
    for (var i = 0; i < events.length; i++){
        if (immediate && !timeout) func.apply(this, arguments);
        clearTimeout(timeout); // does not do anything if timeout is null.
        timeout = setTimeout(function(){
            timeout = null;
            if (!immediate) func.apply(this, arguments);
        }
    }
    

    You see the timeout is available to the next iteration? And there is no reason, in my opinion to rename this to content and arguments to args.

提交回复
热议问题