XMLHttpRequest点击太多-脚本崩溃(JavaScript)

XMLHttpRequest too many clicks - script crashes (JavaScript)

本文关键字:崩溃 JavaScript 脚本 太多 XMLHttpRequest      更新时间:2023-09-26

我有一个问题与以下JavaScript函数:

function blablabla(str) {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp_move = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
   xmlhttp_move = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp_move.onreadystatechange = function() {
    if (xmlhttp_move.readyState == 4 && xmlhttp_move.status == 200) {
      document.getElementById("inventory").innerHTML = xmlhttp_move.responseText;
    }
  }
  xmlhttp_move.open("GET","/m/inventory.php?id="+str,true);
  xmlhttp_move.send(); 
}

当用户不停地点击太多次,没有等待重新加载,他看到网站崩溃(我的意思是样式改变…因为我猜函数返回空结果到DIV)这是解决这个问题的聪明方法?我读过一些关于使用open(…), false)但我想保持异步功能

我倾向于"揭穿"你的blablabla函数。

脱包是一种防止函数被快速连续多次调用的技术。例如,"这个函数每秒只能被调用一次"。时间阈值由你决定。

下面是一个简单的debounce函数,用纯JavaScript编写(不依赖库):
function debounce(fn, threshold) {
    threshold = threshold || 300;
    var timer;
    return function() {
        if (!timer) {
            fn.apply(this, arguments);
        }
        clearTimeout(timer);
        timer = setTimeout(function() {
            timer = null;
        }, threshold);
    };
};

使用率(阈值设置为1秒):

debounce(blablabla, 1000);

的例子:

var el = document.getElementById('myid');
el.addEventListener('click', debounce(blablabla, 1000));

进一步阅读:

  • http://davidwalsh.name/function-debounce
  • 有人能解释一下"脱线"吗?函数