我有一个滑块,它使用以下代码行将其值发送到web服务器:
window.location = "http://172.20.2.1:83/trigger/1?" + value;
这段代码在我的TestSlider(value)函数中,该函数是从某个范围的onchange事件调用的。
问题是,当我移动滑块时,我正在向web服务器发送大量数据。
我想创建一个发送最近值的缓冲区。我已经创建了一个计时器函数,目前我很高兴它能够每秒计时一次。它应该获取公共变量值,并暂时将其写入日志。
然而,我看到的问题是,它仍然在向日志中写入大量数据,因此它肯定会使我的web服务器崩溃。
下面是我的javascript:
//Put a timer in to work as buffer. This should stop the lpc crashing. I think its
//as a result of to much data.
var c=0;
var t;
var timer_is_on=0;
// Holy Smoke Hacked...liked a pro!
calculateHost();
var ip = getControllerIP();
var triggerNumber = 1;
var Value;
function timedCount()
{
//console.log("Timer Ticked: " + c + "URL : " + url); //Write tick value and url to log.
c=c+1; //Add 1 to tick value.
t=setInterval("timedCount()",10000); //Set the old interval.
console.log(c);
}
function doTimer()
{
timer_is_on=1;
timedCount();
}
function testSlider(value)
{
var url = (ip + "/trigger/" + triggerNumber + "?" + value);
//Removed because its it would be better to see when the timer is executing.
//console.log(url);
Value = value;
//Removed because we need a buffer.
//window.location = "http://172.20.2.1:83/trigger/1?" + value;
}
发布于 2011-04-01 11:55:15
这个解决方案被称为去抖动。
这个想法是只对一系列重复事件中的最后一个事件做出反应。
在这里阅读所有关于反弹力事件的信息:http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
另一种解决方案是限制事件,从而在每个设置的时间间隔仅对事件作出反应。
您可以使用以下函数原型扩展来限制事件处理程序,在上面的链接中查找去抖动逻辑:
Function.prototype.throttle = function throttle(delay) {
var func = this, timeOfLastExec = 0, execWaiting = false;
return function throttled() {
var context = this, args = arguments, timeSinceLastExec = new Date().getTime() - timeOfLastExec;
function exec() {
execWaiting && clearTimeout(execWaiting);
execWaiting = false;
timeOfLastExec = new Date().getTime();
func.apply(context, args);
}
if (timeSinceLastExec >= delay) {
exec();
}
else if (!execWaiting) {
execWaiting = setTimeout(exec, delay - timeSinceLastExec);
}
};
};
发布于 2011-04-01 11:40:29
我认为更好的方法是使用onMouseUp
事件-这将只在滑块释放时向服务器发送数据,从而只发送一个请求。
发布于 2011-04-01 11:54:15
计时器的问题是,您在timer事件的处理程序中启动了另一个计时器。在第一轮之后,你有两个定时器,然后是4,8,16,32,64,128,256,512,依此类推...过不了多久,你的计时器就会比浏览器处理的时间还要多,所有这些都会把数据发送到你的服务器上(如果你已经实现了的话)。
https://stackoverflow.com/questions/5512829
复制相似问题