admin管理员组

文章数量:1391987

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?

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?

Share Improve this question edited Oct 8, 2017 at 15:03 Cœur 38.8k25 gold badges206 silver badges278 bronze badges asked Sep 28, 2015 at 18:11 traptrap 2,6407 gold badges27 silver badges45 bronze badges 2
  • 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 Commented Sep 28, 2015 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 plete of ajax call again with the time interval you want. – rkmorgan Commented Sep 28, 2015 at 18:30
Add a ment  | 

1 Answer 1

Reset to default 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);

本文标签: javascriptajax call to REST serviceSet IntervalStack Overflow