使用Javascript对每次15秒的ajax调用进行速率限制和排队 [英] Using Javascript to rate limit and queue ajax calls to once every 15 seconds

查看:121
本文介绍了使用Javascript对每次15秒的ajax调用进行速率限制和排队的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,每次用户执行某些操作时都会自动发送推文...

I have an application that automatically tweets every time a user does something...

如果愿意,用户可以每秒轻松执行一次该操作。

Users can easily perform that action once every second if they like.

Twitters速率限制表示它注意到15分钟内发生了多少推文。从技术上来说,我认为我总是低于15分钟,但似乎twitter也说嘿,你可以在15分钟内发布15个帖子,但15秒内不会发布15个帖子......这是合理的,我认为...

Twitters rate limit says that it pays attention to how many tweets happen in 15 minutes. Technically I think I am always below the 15 minute mark, but it seems like twitter also says "hey you can post 15 posts in 15 minutes, but not 15 posts in 15 seconds"... which is reasonable I think...

我想在javascript端解决这个问题。我想有一个函数数组,我添加而不是实际调用ajax,然后有一个setTimeout外观,检查是否在数组的开头有一个函数调用,运行该函数,删除它从阵列中等待15秒再做一次。

I would like to solve this problem on javascript side. I would like to have an array of functions, that I add to rather than actually calling the ajax, and then have a setTimeout look that checks to see if there is a function call at the beginning of the array, runs that function, removes it from the array and waits 15 seconds to do it again.

这将会使推文(ajax调用)随着时间推移变得合理。

This will serve to slow down the tweets (ajax calls) over time to something reasonable.

这似乎就像我应该用库解决的东西,但我见过的限制库似乎正好适应忽略而不是存储中间请求。 jquery上的队列函数似乎是用于动画而且似乎过于复杂,但可能是正确的回答...

This seems like something I should be solving with a library but the throttling libraries that I have seen seem to geared up to ignore rather than store intermediate requests. The queue function on jquery seems to be for animation and seems over complex, but might be the right answer...

想法?

推荐答案

跟我一起去这个

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Queue things</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var myQueue=[],msgNum=0;
function queueIt(item) {
  myQueue.push({ "item":item, "ts":new Date().getTime()});
}
function processQueue() {
  if (myQueue.length===0) return;
  var obj = myQueue.shift();
  $("#content").append('<br/>'+obj.item+" "+diff(obj.ts));
}
function diff(ts) {
    var t = new Date().getTime()-ts;
    return t + "ms ago";
}
$(function(){
    $("#clickMe").on("click",function() {
        msgNum++;
        queueIt("Message #"+msgNum);
    });
    setInterval(processQueue,15000);
});

</script>
</head>
<body>
<input type="button" id="clickMe" value="Queue something"/>
<div id="content"></div>
</body>
</html>

这篇关于使用Javascript对每次15秒的ajax调用进行速率限制和排队的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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