我有一个通过AJAX调用自动保存其内容的元素。目前,每当内容改变时,调用自动保存功能。但是,我想稍微限制一下以减少服务器请求的数量。编辑以下代码的最佳方法是什么,因此每n秒调用save()
不超过一次?
$("#editorInstance").contentChange(function() {
save();
});
答案 0 :(得分:3)
如果你不介意另一个库,下划线有throttle
method可以处理这个:
节流
_.throttle(function, wait)
创建并返回传递函数的新的受限制版本,当重复调用时,每次等待毫秒时,实际上最多只调用一次原始函数。对于速度限制事件非常有用,这些事件的发生速度比您能跟上的速度要快。
var throttled = _.throttle(updatePosition, 100); $(window).scroll(throttled);
答案 1 :(得分:2)
您可以使用setTimeOut()
延迟函数的执行var init;
$("#editorInstance").contentChange(function() {
init = setTimeOut(save, 60000); //After a minutes
});
//Do you forget to clear the timeout too
function save() {
clearTimeOut(init);
//Remaining function
}
或者,您可能希望在保存编辑器时禁用它。
$("#editorInstance").contentChange(function() {
$(this).attr('disabled', true);
save();
$(this).removeAttr('disabled');
});
答案 2 :(得分:1)
这就是我解决它的方法,
$("#editorInstance").contentChange(function() {
if(!window.saveTimeout)
window.saveTimeout = setTimeOut(save(), 60000);
else
clearTimeout(window.saveTimeout);
window.saveTimeout = setTimeOut(save(), 60000);
});