Ankur Gupta
Ankur Gupta

Reputation: 335

Setting clearTimeOut

Let me know the difference between setting clearTimeout and setting the same variable as null which is used for setting the id of settimeout.

I have seen a function in underscore.js mentioned below.

 function debounce(func, wait, immediate) {
    var timeout, args, context, timestamp, result;

    var later = function() {
        var last = new Date().getTime() - timestamp;

        if (last < wait && last >= 0) {
            timeout = setTimeout(later, wait - last);
        } else {
            timeout = null;
            if (!immediate) {
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            }
        }
    };

    return function() {
        context = this;
        args = arguments;
        timestamp = new Date().getTime();
        var callNow = immediate && !timeout;
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
            result = func.apply(context, args);
            context = args = null;
        }

        return result;
    };
};

It ultimately sets "timeout" variable as "null" instead of using clearTimeOut.

Upvotes: 2

Views: 915

Answers (1)

PaulBGD
PaulBGD

Reputation: 2084

clearTimeout actually cancels the scheduled function if it hasn't ran yet. So when it.

This piece of code is setting timeout to null when the scheduled time is before the current time, so it sets it to null to clear the value so that the other code knows that there's no timeout waiting. Because this piece of code doesn't need to cancel the timeout, it doesn't use clearTimeout.

Basically, clearTimeout and unsetting a variable have nothing to do with each other.

Upvotes: 1

Related Questions