如何防止JQuery中过多的函数调用 [英] How to prevent excessive function calls in JQuery
问题描述
我有一个通过AJAX调用自动保存其内容的元素.当前,每当内容更改时,都会调用自动保存功能.但是,我想对此加以限制,以减少服务器请求的数量.最好的编辑以下代码的方式是什么,以便每n秒调用一次save()
不多?
I have an element which autosaves its contents via an AJAX call. Currently, whenever the contents change the autosave function is called. However, I'd like to limit this a bit to reduce the number of server requests. What would be the best way of editing the following code so save()
is called no more than once every n seconds?
$("#editorInstance").contentChange(function() {
save();
});
推荐答案
如果您不介意其他库,则下划线具有 throttle
方法可以处理此问题:
If you don't mind another library, underscore has a throttle
method which can handle this:
油门
_.throttle(function, wait)
创建并返回传递的函数的新的受限制版本,当反复调用该函数时,每等待毫秒最多只能实际调用一次原始函数.对于发生比您能跟上的速度更快的限速事件很有用.
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);
这篇关于如何防止JQuery中过多的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!