私はあなたのアプローチを使用すると、各キーストローク上のサーバにリクエストを送信しているので、サーバーをあふれさせるために起こっていると思います。 @SravanSが言ったようにクライアント側でリクエストを中止したとしても、サーバーは引き続きこれらのすべてを処理し始めます。一度送信されたHTTPリクエストは既にネット上にありますが、止めることはできません。クライアント側では中止する必要はありません。サーバーに通知するか、送信したレスポンスを無視するだけですが、それ。
ユーザーが入力をやめたことを認識するための遅延を実装するのが最善の方法でしょう。これはジェネリック遅延イベントハンドラファクトリです。本当に使いやすく、関数を渡して遅延を割り当てるだけです。キーストロークの間にXミリ秒が経過した場合、リクエストが送信されますが、その遅延の前に別のキーストロークが発生した場合でも、リクエストはしません。
function delayedEvent(eventHandler, delay) {
var lastTimeout = null;
return function() {
var that = this,
args= Array.prototype.slice.call(arguments).sort();
if (lastTimeout !== null)
window.clearTimeout(lastTimeout);
lastTimeout = window.setTimeout(function() {
eventHandler.apply(that, args);
}, delay);
};
}
$('... selector ...').on('event', delayedEvent(function() { ... your code ... }, 500));
EDIT:これはキューを実装する方法ですが、私は出発点としてそれを使用し、このコードをテストしていません。
function eventQueue(requestMaker) {
// Here we store the last event queued, it'll wait until all the already running events are done.
var lastQueued = null,
runningQueue = [];
// Push a new event into the running queue
function pushRunning(toPush) {
runningQueue.push(toPush.done(
// It is necesary to use an IIFE to get the index by value and not by reference
(function (index) {
return function() {
// Remove this event from the runningqueue
runningQueue.splice(index, 1);
// If the queue has been completed, start running the last event sent
if (lastQueued !== null && runningQueue.length === 0) {
pushRunning(lastQueued());
}
}
}(runningQueue.lenght));
));
}
return function() {
var that = this,
args = Array.prototype.slice.call(arguments).sort();
// Some events are already running, just override the lastQueued
if (runningQueue.length > 0) {
lastQueued = requestMaker.bind(that, args);
} else {
// Nothing queued run this event straight away, and queue it as running
pushRunning(requestMaker.apply(that, args));
}
};
}
$('... selector ...').on('event', eventQueue(function() {
// It's extremely important that you return the jquery $.ajax Promise
return $.ajax(...);
}, 500));
ありがとう、しかし、私はクライアント側でキューを処理したいだけ明確にする。したがって、キーストロークのいくつかは決してサーバーに送信されません。以前のキーストロークがサーバー側で処理されている間に最後に行われたキーストロークのみがクライアント側から送信される必要があります。 – ChristofferJoergensen
申し訳ありませんが、いくつかのことは私に感動しません。あなたの質問では、要求を待ち行列に入れたいとし、キーストロークが起きたときにその要求を待ち行列の最初の位置に入れてください。最後のキューをキューの最上部に置いても、最初の要求は前に到着しますが、それは意味をなさないので、それを行うことで何も得られません。また、あなたのコメントでは、サーバーがすでにリクエストを処理している最中に、最後のキーストロークをクライアントから送信しないように言っていますか?あなたが最後のものを送ったなら、それはすでに何かを処理していますか?それは私の答えなんです。 –
** 1)** 'キーストローク1 'が発生し、'要求a'を引き起こす** 2)** 'キーストローク2'は起こるが、'応答a 'がまだ発生していないのでキューに入れられる** 3)** 'キーストローク3 'が発生し、キュー内の ''キーストローク2' 'を置き換える。** 4) '応答a'が発生するので、 'キーストローク3'を含む'要求b 'がトリガされる。 – ChristofferJoergensen