How To Check For New Tweets From a User

It’s very easy to check if a user has posted a new tweet with JQuery. You will be using getJSON along a new native javascript function which you might not have heard of.

This is how your script is going to work:

  • Each Tweet has a different ID.
  • Make a variable to store this ID.
  • Read the stream of tweets and assign the first tweet’s ID to this variable.
  • Continue to read the stream at specified time intervals.
  • If the ID of the first tweet has changed show the new tweet and assign its ID to the tweet ID variable.

The HTML: For Display New Tweets

We are going to need a div where we will display the tweets.

<div id="tweet">

</div>

That’s it!

The JQuery: To Check For New Tweets

I want to read a stream from a specific user, the “formula” for that is the following.

http://api.twitter.com/1/statuses/user_timeline/username.json

But if am reading from JQuery I need a callback function.

http://api.twitter.com/1/statuses/user_timeline/username.json?callback=?

Yes, the callback function is a question mark. And no, you don’t need to make a question mark function in your script.

I have mad three appropriately named variables for my script.

	var oldTweetId=0;
	var username='myusername';
	var url='http://api.twitter.com/1/statuses/user_timeline/'+username+'.json?callback=?';

Now let’s make the function used to check tweets and assign ids, I’ve call id “checkStream”

	function checkStream()
	{
		$.getJSON(url,function(tweets){
			if(tweets[0].id!=oldTweetId)
			{
				// new tweets
				$("div#tweet").append('

'+tweets[0].text+'

'); // append tweet to tweet div
				oldTweetId=tweets[0].id; // update tweet id
			}
		});
	}

How Execute a Function at Intervals

Now what I need to do is execute the function checkStream() at a certain time interval, to this I will use Javascript’s setInterval function.

The function setInterval takes two parameters, the name of the function you want to execute and the time, in milliseconds at which you wish to execute it.

This is my setInterval set up, it will check for new tweets every two seconds

	setInterval(checkStream, 2000);

The Full Script

For the lazy or impatient here is the full script, enjoy!

<html>
<head>
</head>
<body>
<div id="tweet">

</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	var oldTweetId=0;
	var username="username";
	var url='http://api.twitter.com/1/statuses/user_timeline/'+username+'.json?callback=?';

	setInterval(checkStream,5000);

	function checkStream()
	{
		$.getJSON(url,function(tweets){
			if(tweets[0].id!=oldTweetId)
			{
				// new tweets
				$("div#tweet").append('<p>'+tweets[0].text+'</p>');
				oldTweetId=tweets[0].id;
			}
		});
	}
});
</script>
</body>
</html>