我在使用以下 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
函数。
去抖动是一种防止函数快速连续多次调用的技术。例如,“该函数每秒调用次数不得超过一次”。时间阈值由您决定。
这是一个简单的去抖函数,用纯 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));
进一步阅读:
关于javascript - XMLHttpRequest 点击次数过多 - 脚本崩溃 (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517459/