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

1

3

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?

Forgot answered 9/7, 2013 at 6:17 Comment(3)
It sounds quite straight forward. Instead of tweeting, push to array and have a simple setTimeout pop to twitter - only thing is keeping the user on the page if he wants to leave before all tweetedGelhar
... and taking @mplungjan's answer further, you might even make it so that you collate tweets into a queue, but instead of shooting out a single tweet every 15 seconds, you can aggregate all pending tweets into a vector every 15 seconds. This way, the "loss" of leaving early is minimized. I'm not familiar with Twitter's API, but I'd half expect that pushing tweets to their API would have some capacity for vectorization. Pretty interesting.Protonema
Any chance you would return and comment?Gelhar
G
2

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>
Gelhar answered 9/7, 2013 at 8:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.