I want to make an AJAX call about 2000ms. My AJAX is fired up once user clicks on anchor tag. So after that I want that AJAX to run every 2000ms.

setInterval(function(){
$("a[name=device_submit]").click(function(event){
    var get_url = $(this).attr('href');
    event.preventDefault();
    $.ajax({url:get_url,
     success:function(data){
         var data = JSON.parse(data);
         latitude = data[0].fields.latitude;
         longitude = data[0].fields.longitude;
         initialize(latitude, longitude, 15);
  }});
});
}, 2000);

Problem is, it's running lot of times, when I click it, it stops then. Then again when I click it it runs lot of times. What's wrong?

有帮助吗?

解决方案 2

Don't constantly re-bind your click handler, if you're looking to fire off AJAX every 2 seconds, something like the following should do. I added a flag so that the AJAX won't fire until you first click the button (untested, the braces may be off)

var flag = false;

var url = $("a[name=device_submit]").attr('href');

a["name=device_submit]").click(function(e){
    e.preventDefault();
    flag = true;
});

setInterval(function(){
 if(flag){
  $.ajax({url:url,

   success:function(data){
     var data = JSON.parse(data);
     latitude = data[0].fields.latitude;
     longitude = data[0].fields.longitude;
     initialize(latitude, longitude, 15);

  });
 }
}, 2000);

其他提示

Your interval is binding the event handler each time it fires.

Swap setInterval with click

$("a[name=device_submit]").click(function(event) {
    setInterval(function() {
        var get_url = $(this).attr('href');
        event.preventDefault();
        $.ajax({
            url: get_url,
            success: function(data) {
                var data = JSON.parse(data);
                latitude = data[0].fields.latitude;
                longitude = data[0].fields.longitude;
                initialize(latitude, longitude, 15);

            });
        }
    }, 2000);
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top