title: How to overwrite/cancel previous promise called one by one?
body: <p>I have jQuery code that respond to user keyboard press and I'm checking if element is in view. The plugin return promise if user press the key very fast or hold it (right now it's too fast for my code) it create promise in kind of loop. I want to cancel previous promise before I call new one.</p>
  
  <p>I came up with this code that ignores previous promise:</p>
  
  <pre><code>var scroll_callback_counter = 0;
  function move_cursor_visible() {
      var cursor = self.find('.cursor');
      var i = scroll_callback_counter++;
      return cursor.is_fully_in_viewport(self).then(function(visible) {
          if (i === scroll_callback_counter &amp;&amp; !visible) {
              var offset = cursor.offset();
              var container_offset = self.offset();
              self.scrollTop(offset.top - container_offset.top - 5);
              return true;
          }
      });
  }
  </code></pre>
  
  <p>Is there a better way? It works but I don't know if this is correct way to create code that cancel/ignore promise callback.</p>
  
  <p>EDIT:</p>
  
  <p>Here is <code>is_fully_in_viewport</code> function:</p>
  
  <pre><code>function jquery_resolve(value) {
      var defer = jQuery.Deferred();
      defer.resolve(value);
      return defer.promise();
  }
  $.fn.is_fully_in_viewport = (function() {
      function is_visible(node, container) {
          var box = node.getBoundingClientRect();
          var viewport = container[0].getBoundingClientRect();
          var top = box.top - viewport.top;
          var bottom = box.bottom - viewport.top;
          var height = container.height();
          return bottom &gt; 0 &amp;&amp; top &lt;= height;
      }
      if (window.IntersectionObserver) {
          return function(container) {
              var node = this[0];
              var defer = jQuery.Deferred();
              var item_observer = new window.IntersectionObserver(function(entries) {
                  defer.resolve(entries[0].isIntersecting);
                  item_observer.unobserve(node);
              }, {
                  root: container[0]
              });
              item_observer.observe(node);
              return defer.promise();
          };
      } else {
          return function(container) {
              return jquery_resolve(is_visible(this[0], container));
          };
      }
  })();
  </code></pre>