问题描述
我对以下JavaScript函数有疑问:
I have a problem with the following JavaScript function:
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)的文章,但我想保持异步功能.
When user clicks too many times non-stop, without waiting reload at some point he sees website crash (i mean styling changes.. as I guess function returns empty result into DIV) which is the smart way to fix this problem? I've read some articles about using open(.., false) but i'd like to keep asynchronized function.
推荐答案
我倾向于去抖动"您的blablabla
函数.
I would be inclined to "debounce" your blablabla
function.
去抖是一种防止快速连续多次调用功能的技术.例如,每秒最多调用一次此功能".时间阈值由您决定.
Debouncing is a technique to prevent a function being called multiple times in quick succession. "This function may be called no more than once per second", for example. The time threshold is up to you.
这是一个简单的反跳功能,用纯JavaScript编写(无库依赖性):
Here's a simple debounce function, written in plain JavaScript (no library dependencies):
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秒):
Usage (threshold set at 1 second):
debounce(blablabla, 1000);
示例:
var el = document.getElementById('myid');
el.addEventListener('click', debounce(blablabla, 1000));
进一步阅读:
- http://davidwalsh.name/function-debounce
- Can someone explain the "debounce" function in Javascript
这篇关于XMLHttpRequest点击次数过多-脚本崩溃(JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!