Display Justin Bieber Tweets with Asynchronous Recursion


/ Published in: JavaScript
Save to your folder(s)

Just a fun and silly way to asynchronously update tweets about Justin Bieber.


Copy this code and paste it in your HTML
  1. <!DOCTYPE html>
  2.  
  3. <html lang="en">
  4. <head>
  5. <meta charset="utf-8">
  6. <title>The Biebster</title>
  7. </head>
  8. <body>
  9.  
  10. <h2> Latest Biebster Tweets </h2>
  11. <ul id="tweets"> </ul>
  12.  
  13. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  14.  
  15. <script>
  16.  
  17. (function() {
  18. var UpdatePanel = {
  19. init : function(options) {
  20. this.options = $.extend({
  21. interval : 5000,
  22. number : 3,
  23. hijackTweet : false
  24. }, options);
  25.  
  26. this.updater();
  27. },
  28.  
  29. updater : function() {
  30. (function updateBox() {
  31. this.timer = setTimeout(function() {
  32. updateIt();
  33. updateBox();
  34. }, UpdatePanel.options.interval);
  35. })();
  36.  
  37. // get the ball rolling
  38. updateIt();
  39.  
  40. function updateIt() {
  41. $.ajax({
  42. type : 'GET',
  43. url : UpdatePanel.options.url,
  44. dataType : 'jsonp',
  45.  
  46. error : function() {},
  47.  
  48. success : function(results) {
  49. var theTweets = '',
  50. elem = UpdatePanel.options.elem.empty();
  51.  
  52.  
  53. $.each(results.results, function(index, tweet) {
  54. if ( UpdatePanel.options.hijackTweet ) {
  55. tweet.text = tweet.text.replace(/(Justin )?Bieber/ig, 'Nettuts');
  56. }
  57.  
  58. if ( index === UpdatePanel.options.number ) {
  59. return false;
  60. }
  61. else {
  62. theTweets += '<li>' + tweet.text + '</li>';
  63. }
  64. });
  65. elem.append(theTweets);
  66. }
  67. });
  68. }
  69. },
  70.  
  71. clearUpdater : function() {
  72. clearTimeout(this.timer);
  73. }
  74. };
  75. window.UpdatePanel = UpdatePanel;
  76. })();
  77.  
  78. UpdatePanel.init({
  79. interval : 5000,
  80. number : 5,
  81. url : "http://search.twitter.com/search.json?q=bieber",
  82. elem : $('#tweets'),
  83. hijackTweet : true
  84. });
  85.  
  86. </script>
  87. </body>
  88.  
  89. </html>

URL: http://net.tutsplus.com/tutorials/javascript-ajax/how-to-display-justin-bieber-tweets-with-asynchronous-recursion/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.