-1
   debounceFunction() {
        let timeout = setTimeout(() => {
            doSomething();
            flag = true;
            clearTimeout(timeout);
        }, 250);
    }

I wrote a debounce function that looks like the above, I called this function for several times when an event is triggered. My question is, does the clearTimeout at the end of the setTimeout makes any sense?

What would be the optimal way to do it?

Thanks in advance :)

Laiacy
  • 1,504
  • 13
  • 18

3 Answers3

0

Does the clearTimeout at the end of the setTimeout make any sense?

No, there's no point to call clearTimeout from within the setTimeout callback - it's too late there already. You cannot clear anything, the timeout already occurred.

clearTimeout is used when you want to prevent the callback from getting called before that would happen.

What would be the optimal way to do it?

Just omit it.

If you are asking about the optimal way to write debounce, see Can someone explain the "debounce" function in Javascript.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

My question is, does the clearTimeout at the end of the setTimeout makes any sense?

No, clearTimeout is used to clear the previous created timeout, so clearTimeout should be done before setTimeout in order to cancel out previous invocation of setTimeout.

What would be the optimal way to do it?

Have a look David Walsh's post and SO question

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

clearTimeout() prevents the execution of the function that has been set with setTimeout(); In debouncing, a user is made to perform limited actions in a time interval. So we set that action inside a function within setTimeout and whenever the user tries to perform the same action within the given interval, we call clearTimeout to prevent user from doing it. So clearTimeout should be called before SetTimeout.