Perform function every second

Perform function every second

I have created a page that grabs some data from a php page every second using a timer. However, I am pretty sure there is a way to make the code a lot shorter and neater, perhaps using a loop.

Here is the code

  1. <script type="text/javascript">

  2. $(document).ready(function() {
  3. var delay = 10 ;
  4. function countdown() {
  5. setTimeout(countdown, 1000) ;
  6. $('#countmesg').html("Ends in "  + delay  + " seconds.");
  7. delay --;

  8. if (delay == 10 ) {
  9. $.post('grab.php', {name: name}, function(data) {
  10. $('div#name-data').text(data);
  11. });
  12. }

  13. if (delay == 9 ) {
  14. $.post('grab.php', {name: name}, function(data) {
  15. $('div#name-data').text(data);
  16. });
  17. }

  18. if (delay == 8 ) {
  19. $.post('grab.php', {name: name}, function(data) {
  20. $('div#name-data').text(data);
  21. });
  22. }

  23. if (delay == 7 ) {
  24. $.post('grab.php', {name: name}, function(data) {
  25. $('div#name-data').text(data);
  26. });
  27. }

  28. if (delay == 6 ) {
  29. $.post('grab.php', {name: name}, function(data) {
  30. $('div#name-data').text(data);
  31. });
  32. }

  33. if (delay == 5 ) {
  34. $.post('grab.php', {name: name}, function(data) {
  35. $('div#name-data').text(data);
  36. });
  37. }

  38. if (delay == 4 ) {
  39. $.post('grab.php', {name: name}, function(data) {
  40. $('div#name-data').text(data);
  41. });
  42. }

  43. if (delay == 3 ) {
  44. $.post('grab.php', {name: name}, function(data) {
  45. $('div#name-data').text(data);
  46. });
  47. }

  48. if (delay == 2 ) {
  49. $.post('grab.php', {name: name}, function(data) {
  50. $('div#name-data').text(data);
  51. });
  52. }

  53. if (delay == 1 ) {
  54. $.post('grab.php', {name: name}, function(data) {
  55. $('div#name-data').text(data);
  56. });
  57. }




  58. if (delay < 0 ) {
  59. $('#countmesg').html("Auction ended.");
  60. delay = 0 ;
  61. }
  62. }
  63. countdown() ;
  64. });
  65. </script>