[英]Restrict amount of times jQuery slider fires change event?
I have the problem that the jQuery mobile slider fires too often to get handled properly on the server. 我有一个问题,即jQuery移动滑块经常触发以在服务器上正确处理。 I have something like this: 我有这样的事情:
$("#testSlider").change(function( event, ui ) {
$.getJSON($SCRIPT_ROOT + '/_update_sliders', {
c: $('#testSlider').val()
}, function(data) {
g4.updateOptions( { 'file': data.result } );
});
This works perfectly fine, /_update_sliders starts a function in python which sends data.result back to the site. 这很好用,/ _update_sliders在python中启动一个函数,它将data.result发送回站点。 The problem occurs if I change the slider too fast - too many requests are send, when I stop the slider it takes quite some time too catch up and it even mixes up the requests - so the end state might not even present the actual slider value. 如果我更快地更改滑块会发生问题 - 发送的请求太多,当我停止滑块时需要花费相当长的时间才赶上它甚至混淆请求 - 所以结束状态甚至可能不会显示实际的滑块值。
What is a clean solution to this? 什么是干净的解决方案? Anyway to restrict the amount of times the change event fires up? 无论如何要限制变更事件发生的次数?
Thank you and kind regards 谢谢你,亲切的问候
lakerz lakerz
You could put a throttle on it using following concept. 您可以使用以下概念为其加油门。 Uses setTimeout() to add delay, and if changes are constantly happening delay gets pushed back and it will not fire until a full delay period has ended 使用setTimeout()来添加延迟,如果不断发生更改,延迟会被推迟,直到完整延迟时间结束才会触发
var sliderTimer,
sliderAjaxDelay = 100;
$("#testSlider").change(function (event, ui) {
if (sliderTimer) {
clearTimout(sliderTimer); /* if already a timeout, clear it */
}
// throttle requests using setTimeout
sliderTimer = setTimeout(sliderAjaxUpdate, sliderAjaxDelay);
});
function sliderAjaxUpdate() {
$.getJSON($SCRIPT_ROOT + '/_update_sliders', {
c: $('#testSlider').val()
}, function (data) {
g4.updateOptions({
'file': data.result
});
});
}
Adjust the delay variable to what suits you 调整延迟变量以适合您
I found a solution in jQuery which works, but I'm not sure if this is a "clean" way: 我在jQuery中找到了一个有效的解决方案,但我不确定这是否是一种“干净”的方式:
var complete = 0;
$("#testSlider").change(function (event, ui) {
if (complete == 1) {
sliderAjaxUpdate();
complete = 0;
};
});
function sliderAjaxUpdate() {
$.getJSON($SCRIPT_ROOT + '/_update_sliders', {
c: $('#testSlider').val()
}, function (data) {
g4.updateOptions({
'file': data.result
});
});
};
$( document ).ajaxComplete(function() {
complete = 1;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.