3

From the self Host I want to get the data after every 5 seconds.

My Code in request.js:

    $.ajax({
        type: "GET",
        url: "http://localhost:8080/api/Data",
        success: function (data) {
            console.log(data);
        }
    });

What do I have to add?

Cœur
  • 37,241
  • 25
  • 195
  • 267
trap
  • 2,550
  • 7
  • 21
  • 42
  • the setInterval of course. Unless you wanted to do it in such a way that prevents errors when it takes longer than the interval, in which case you'd use setTimeout. – Kevin B Sep 28 '15 at 18:22
  • In my code I prefer setTimeout instead of setInterval if there is ajax call in the code. setInterval might cause issues if the return call takes more than the time interval. call back setTimeout() on complete of ajax call again with the time interval you want. – rkmorgan Sep 28 '15 at 18:30

1 Answers1

7

Write function and set it to setInterval:

function checkData() {
    $.ajax({
        type: "GET",
        url: "http://localhost:8080/api/Data",
        success: function (data) {
            console.log(data);
        }
    });
}

setInterval(checkData, 5000);

you can use setTimeout if your ajax call gets longer time to get response:

function checkData() {
    $.ajax({
        type: "GET",
        url: "http://localhost:8080/api/Data",
        success: function (data) {
            console.log(data);
            setTimeout(checkData, 5000);
        }
    });
}

setTimeout(checkData, 5000);
kakajan
  • 2,614
  • 2
  • 22
  • 39
  • 1
    __important note:__ `setInterval` is for _periodic_ updates, however `setTimeout` is just for delays, it will fire _only once_, for more info check this question: http://stackoverflow.com/questions/729921/settimeout-or-setinterval – mergenchik Sep 29 '15 at 20:24