如何在JQuery中防止过多的函数调用

我有一个元素通过AJAX调用自动保存其内容。 目前,每当内容改变时,调用自动保存function。 但是,我想稍微限制一下以减少服务器请求的数量。 编辑以下代码的最佳方法是什么,因此每隔n秒调用save()不超过一次?

 $("#editorInstance").contentChange(function() { save(); }); 

如果你不介意另一个库,下划线有一个可以处理这个的throttle方法 :

油门 _.throttle(function, wait)

创建并返回传递函数的新的受限制版本,当重复调用时,每隔等待毫秒最多只调用一次原始函数。 对于速度限制事件非常有用,这些事件发生得比您能跟上的速度要快。

 var throttled = _.throttle(updatePosition, 100); $(window).scroll(throttled); 

您可以使用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'); }); 

这是我解决它的方式,

 $("#editorInstance").contentChange(function() { if(!window.saveTimeout) window.saveTimeout = setTimeOut(save(), 60000); else clearTimeout(window.saveTimeout); window.saveTimeout = setTimeOut(save(), 60000); });