When is the 'remaining > wait' conditional statement ever true in underscore.js's implementation of throttle?

Library code (line 860 in question): https://github.com/jashkenas/underscore/blob/master/underscore.js

if (remaining <= 0 || remaining > wait)

When is the second half of this true?

Background - first post on SO and pretty new to javascript coding. I've reimplemented throttle from scratch as an exercise and I'm comparing my version to the library function. I don't understand why this part of the conditional statement exists in the library function because it appears to me that it will never be true, so I think I'm missing something. Can someone fill me in by providing a situation where the referenced statement is true?

I've run it through a debugger and googled for articles but haven't found an answer.

Full library function:

_.throttle = function(func, wait, options) {
    var timeout, context, args, result;
    var previous = 0;
    if (!options) options = {};

    var later = function() {
      previous = options.leading === false ? 0 : _.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };

    var throttled = function() {
      var now = _.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) { // THIS LINE
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };

    throttled.cancel = function() {
      clearTimeout(timeout);
      previous = 0;
      timeout = context = args = null;
    };

    return throttled;
  };

I can't picture 'remaining' ever being greater than 'wait.' When would this happen?

Answers:

Answer

This condition handles the case when the system time was being changed while throttle is in fly.

It may seem like a super edge case but actually there are a lot of reasons time may change. You can change your system time manually or it may be changed automatically (e.g. because of synchronization with ntp server), you can travel and your timezone is changed and of course, don't forget about DST.

I've made a playground where you can investigate it deeper.

This condition was introduced in this commit: Allow _.throttle to function correctly after the system time is updated.

P.S. I faced time-related issues on almost each of my projects and I am very grateful to all these people who think about such things.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.