0

I have the following ajax request that runs when the page is loaded

var city_id = $(".feed-selected-city").attr('id');
    $("#cityfeed").html("<div class='feed-loading'>The feed is loading ...</div>");
    var ajaxOpts = {
            type: "get",
            url: "ajax_getcityfeed.php",
            dataType: 'json',
            data: "&city=" + city_id,
            success: function(data) {
                $('#cityfeed').html(data.data);
            }
        };

    $.ajax(ajaxOpts);

How can I run this piece of code every 10 seconds after that?

  • possible duplicate of [JQuery timer, how do I do this](http://stackoverflow.com/questions/2295049/jquery-timer-how-do-i-do-this) – Madhur Ahuja Jun 06 '11 at 04:41

3 Answers3

0

Use a infinite loop with setTimeout. And put that inside.

Though I don't recommend this to achieve what you're trying todo. I think what you require is some kind of polling; this will probably kill your server if there's a high amount of simultaneous users; since each visitor will send a http request every 10 seconds.

function timedCount()
{
console.log('Hello');
setTimeout("timedCount()",10000);
}

timedCount();
MarioRicalde
  • 9,131
  • 6
  • 40
  • 42
0

Wrap it in a function, and use setTimeout to continuously call the function.

function tick() {
    var city_id = $(".feed-selected-city").attr('id');
    $("#cityfeed").html("<div class='feed-loading'>The feed is loading ...</div>");
    var ajaxOpts = {
            type: "get",
            url: "ajax_getcityfeed.php",
            dataType: 'json',
            data: "&city=" + city_id,
            success: function(data) {
                $('#cityfeed').html(data.data);
            }
        };
    $.ajax(ajaxOpts);
    setTimeout('tick()',10000);
}

$(document).ready(function() {
    tick();
}
Fosco
  • 38,138
  • 7
  • 87
  • 101
  • Is there a way to animate it, so it fades in while the old data fades out? –  Jun 06 '11 at 05:34
0

@Yegor

Wrap the above function using a name. Then use setTimeout(function(){//call the function here},10000); -
I would suggest you not to make this kind of implementation. Make some alternative.