How can I only run an AJAX call on change when the mouse (or finger) is no longer dragging?

落花浮王杯 提交于 2019-12-04 18:12:18
T.J. Crowder

You need to add a bit of hysteresis to your code.

It happens I wrote a generic debounce function for another answer here on SO which would be useful for this.

Here's how you'd use it:

function saveTheData() {
    $.ajax(); ///
}

var saveTheDataDebounced = debounce(50, saveTheData);

function handleIsBeingDragged() {
    saveTheDataDebounced();
}

The debounce function:

// debounce - debounces a function call
//
// Usage: var f = debounce([guardTime, ] func);
//
// Where `guardTime` is the interval during which to suppress
// repeated calls, and `func` in the function to call.
// You use the returned function instead of `func` to get
// debouncing;
//
// Example: Debouncing a jQuery `click` event so if it happens
// more than once within a second (1,000ms), subsequent ones
// are ignored:
//
//    $("selector").on("click", debounce(1000, function(e) {
//      // Click occurred, but not within 1000ms of previous
//    });
//
// Both `this` and arguments are passed through.
function debounce(guardTime, func) {
  var last = 0;

  if (typeof guardTime === "function") {
    func = guardTime;
    guardTime = 100;
  }
  if (!guardTime) {
    throw "No function given to debounce";
  }
  if (!func) {
    throw "No func given to debounce";
  }

  return function() {
    var now = +new Date();
    if (!last || (now - last) > guardTime) {
      last = now;
      return func.apply(this, arguments);
    }
  };
}

You could assign the AJAX call to the "mouseup" event instead. In jQuery mobile "vmouseup".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!