如何限制ajax请求? [英] How to rate-limit ajax requests?

查看:122
本文介绍了如何限制ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有几个div和处理程序在单击它们时发送ajax请求。我的问题是我不知道如何强迫我的处理程序不超过每30秒1个请求的限制。

There are several divs and handler to send ajax requests when they are clicked. My problem is that i don't know how to force my handler not to exceed limit of 1 request per 30 seconds.

感谢您的帮助!

推荐答案

优秀的 Underscore.js 具有油门功能。你传递了你想要限制的处理程序并获得相同函数的速率限制版本。

The excellent Underscore.js has a throttle function. You pass in the handler that you want to throttle and get back a rate-limited version of the same function.

var throttled = _.throttle(someHandler, 100);
$(div).click(throttled);

http://documentcloud.github.com/underscore/#throttle

这是我自己使用的简化版本代码:

Here's a simplified version that I've used in my own code:

function throttle(func, wait) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        if (!timeout) {
            // the first time the event fires, we setup a timer, which 
            // is used as a guard to block subsequent calls; once the 
            // timer's handler fires, we reset it and create a new one
            timeout = setTimeout(function() {
                timeout = null;
                func.apply(context, args);
            }, wait);
        }
    }
}

测试它的好方法是通过触发一堆滚动事件并观察你的处理程序登录到Firebug控制台:

A good way to test it is by firing off a bunch of scroll events and watching your handler log to the Firebug console:

document.addEventListener("scroll", throttle(function() {
    console.log("test");
}, 2000), false); 

这是限制 div s每30秒一次,按要求(需要jQuery):

Here's a version that limits click-events on divs to once every 30 seconds, as requested (requires jQuery):

$("div").click(throttle(function() {
    // ajax here
}, 30000));

这篇关于如何限制ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆