如果没有足够快地完成功能,请停止该功能 [英] stop a function if it doesn't complete quick enough

查看:50
本文介绍了如果没有足够快地完成功能,请停止该功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function which calls to the backend to retrieve information and then displays it. My problem is if the user goes back and forth over many cells, it seems to not catch up in time and display everything the user went over instead of what the current cell is, like its lagging bad displaying multiple elements instead of the intended one. Is there a way to make sure that it only happens to the current cell instead of it lagging bad and catching up?

$('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"的一部分,以检查给定的单元格"是否曾经被处理过,如果没有将结果保存在某个地方,例如存储在data属性中,如果存在则从那里获取(或超出某个时间限制)而不是ajax调用.或在先验"功能中包装防弹跳.

Note you could also as part of your "ajax" check to see if a given "cell" has previously been processed, if not stash the results somewhere - like in a data attribute and get from there if it exists (or is outside some time limit) instead of the ajax call. OR wrap that debounce in that "check prior" functionality.

这篇关于如果没有足够快地完成功能,请停止该功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆