Rickert
Rickert

Reputation: 1675

let ajax data give timeout jquery

ive got the net function:

            var timeout=60000;
    setInterval(function() {

        $.ajax({
          url: "/xheresfm/getstatus.php",
          data: {
          },
          success: function( data ) {
            var obj = jQuery.parseJSON(data);
            timeout=obj.refresh;
          }
        })
    }, timeout);
});

The timeoit is allways 60000, but obj.refresh don't give an empty result, i cant figure out whit it doesn't work.

for example if obj.refresh is 9999999, the timeout is still 60000

Upvotes: 0

Views: 150

Answers (2)

Henry Ruhs
Henry Ruhs

Reputation: 1630

You should not use interval cause if performance issues - it will call and call, call ... call, loop, loooop^^ - not a good idea. What do you think about my approach?

var timeout = 60000;

var refreshStatus = function() {
        $.ajax({
          url: "/xheresfm/getstatus.php",
          success: function( data ) {
            var obj = jQuery.parseJSON(data);

            //do stuff on success
          },
          done: function () {
            setTimeout(function () {
               refreshStatus();
            }, timeout);

          }
        })
    }

refreshStatus();

Upvotes: 0

Ankit Zalani
Ankit Zalani

Reputation: 3168

The reason why your code is not working is that you are using asynchronous call, timout method executes before AJAX call. You can overcome this by using the below code:

var timeout=60000;

var func = function() {
        $.ajax({
          url: "/xheresfm/getstatus.php",
          data: {
          },
          success: function( data ) {
            var obj = jQuery.parseJSON(data);
            timeout=obj.refresh;

            setTimeout(func, timeout);
          }
        })
    }

func();

Hope this helps.

Upvotes: 1

Related Questions