javascript - How can I only run an AJAX call on change when the mouse (or finger) is no longer dragging? -
i have series of interactive sliders change calculated values.
the calculations run on every tiny move of dragged handle (via mousedown or touch drag event).
i need update database values prefer grab values after user "drops" handle.
how can determine if finger or mouse down, in order skip ajax call?
function handleisbeingdragged() { // calculations based on input values here // pseudo-code check mouseup event if (mouseup) { // save if mouse - avoid hundreds of updates per drag event $.ajax(); } }
you need add bit of hysteresis code.
it happens wrote generic debounce
function another answer here on so useful this.
here's how you'd use it:
function savethedata() { $.ajax(); /// } var savethedatadebounced = debounce(50, savethedata); function handleisbeingdragged() { savethedatadebounced(); }
the debounce
function:
// debounce - debounces function call // // usage: var f = debounce([guardtime, ] func); // // `guardtime` interval during suppress // repeated calls, , `func` in function call. // use returned function instead of `func` // debouncing; // // example: debouncing jquery `click` event if happens // more once within second (1,000ms), subsequent ones // ignored: // // $("selector").on("click", debounce(1000, function(e) { // // click occurred, not within 1000ms of previous // }); // // both `this` , arguments passed through. function debounce(guardtime, func) { var last = 0; if (typeof guardtime === "function") { func = guardtime; guardtime = 100; } if (!guardtime) { throw "no function given debounce"; } if (!func) { throw "no func given debounce"; } return function() { var = +new date(); if (!last || (now - last) > guardtime) { last = now; return func.apply(this, arguments); } }; }
Comments
Post a Comment