使用 Javascript 对每 15 秒一次的 ajax 调用进行速率限制和排队

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

本文介绍了使用 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.

Twitter 的速率限制表示它关注 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 调用进行速率限制和排队的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 Javascript 对每 15 秒一次的 ajax 调用进行速率限制和排队

基础教程推荐