Using Javascript to rate limit and queue ajax calls to once every 15 seconds

耗尽温柔 提交于 2019-12-21 02:53:27

问题


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 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...

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.

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

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...

Thoughts?


回答1:


Have a go with this

<!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>


来源:https://stackoverflow.com/questions/17541249/using-javascript-to-rate-limit-and-queue-ajax-calls-to-once-every-15-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!