如果function不够快,请停止一个function

我有一个函数调用后端检索信息,然后显示它。 我的问题是,如果用户在许多单元格中来回移动,它似乎没有及时赶上并显示用户所经过的所有内容而不是当前单元格的内容,例如其显示多个元素而不是预期的单元格。 有没有办法确保它只发生在当前的单元格而不是它滞后并追赶?

$('body').on('mouseenter', '.cell', function (e) { var cellNumber = $(this).attr("cellNumber"); // load the data via ajax $.get('/Main/Sub', { cellNumber: cellNumber }, function(responseText){ // code }).on('mouseout', function(){ $(this).remove(); }); }); 

我会考虑在这里进行辩论。

 // one debounce function, there are several that are similar in form just do a search... function debounce(fn, delay) { var timer = null; return function () { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; } $('body').on('mouseenter', '.cell', debounce(function (event) { // do the Ajax request }, 250)); 

请注意,您也可以作为“ajax”检查的一部分,查看某个给定的“单元格”是否先前已被处理过,如果不是将结果存储在某处 – 比如在数据属性中,如果存在则从那里获取(或者在某个时间之外)限制)而不是ajax调用。 或者在“检查先验”function中包装去抖动。

所以AFAIK一旦完成就无法取消AJAX请求。 您可能想要做的是检查AJAX回调中是否已删除该元素。

 $('body').on('mouseenter', '.cell', function(e) { var cellNumber = $(this).attr("cellNumber"); // load the data via ajax $.get('/Main/Sub', { cellNumber: cellNumber }, function(responseText) { // AJAX has finished double check that this element has not been removed if (this.parentNode) { // node has not been removed, do some cool stuff } }.bind(this)) $(this).on('mouseout', function() { $(this).remove(); }); }); 

看看这个

我讨厌当人们提供最佳实践建议并拒绝回答这个问题时,我已经回答了这个问题,我会给你一些建议哈哈。

我建议不要在鼠标上发送AJAX请求。 用户只需移动鼠标就可以意外触发数百个AJAX请求。 您浪费带宽,CPU,并且您可能会堵塞您的服务器,因为有几个用户移动光标可能会使您的服务器失败。

也许可以考虑将UI / UX更改为单击事件,或者延迟发送ajax,直到光标hover在元素上一段时间。

以前的答案都是正确的,你不能取消机上的ajax请求……但是如果对派对来说太晚了,那就没有什么可以阻止你忽略它。

至少可以使用setTimeout调用来防止这种情况,其中如果响应尚未返回,则setTimeout仅在内部执行whats。

伪代码:

 setTimeout(1000, function(){ window.ignoreResponse = true; }); $.get(something) and then: if (window.ignoreResponse === false) { do x } else { window.ignoreResponse = false; // to reset for the next response } } 

如果这些请求中的多个请求同时运行,您可能只想让ignoreResponse成为引用为对象的时间戳,或者将响应放在列表中,如果有多个请求,则接受最后一个请求。

我相信你的问题的答案在于之前提出的问题。 设置ajax(jQuery)的超时

请查看jquery的ajax文档,但是您可以从下面的代码片段中获取想法:

 $.ajax({ url: "test.html", timeout: 3000 // sets timeout to 3 seconds error: function(){ // will fire when timeout is reached }, success: function(){ //do something }, });