如果函数完成得不够快,请停止函数



我有一个函数,该函数呼叫后端以检索信息然后显示信息。我的问题是,如果用户在许多单元格上来回走动,它似乎不会赶上时间,并且显示了用户所经历的所有内容,而不是当前单元格,就像其滞后差显示多个元素而不是预期的元素一样。有没有办法确保它仅发生在当前单元格上,而不是落后不良并赶上?

$('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调用。或包裹该审问的"检查先验"功能。

所以,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,直到光标悬停在元素上一段时间为止。

以前的答案是正确的n,您无法取消机上的Ajax请求...但是,如果派对为时已晚,没有什么可以阻止您忽略它。

最低限度可以使用setTimeout调用来防止这种情况,而SettieMout仅执行响应尚未返回的情况。

伪代码:

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是一个时间戳,那就是将其引用为对象或将响应放在列表中,如果有一个以上的响应,则将响应放在列表中。

<</p> <。

我相信您的问题的答案在于先前问的问题。设置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
    },
});

最新更新