1

I'm trying to replicate a scenario where a web page contains multiple areas, each being updated by an API call and refreshed every X seconds.

window.setInterval(function() {
  console.log("interval start");
  getData;
  console.log("interval end");
}, 5000);

//for (i = 1; i <= 3; i++) {
//    console.log(i);
//    setTimeout(getData, 5000);
//}

function getData(url, id) {
  console.log("getData start");
  $.get(url, function(data) {
    console.log('data=' + data);
    $(id).html(data);
  });
};

getData('@Url.Action("GetTemperature", "SomeData")', '#temp');
getData('@Url.Action("GetStockPrice", "SomeData")', '#stock');
getData('@Url.Action("GetStateName", "SomeData")', '#state');
getData('@Url.Action("GetARandomDate", "SomeData")', '#myDate');

Here are the logs:

  • getData start
  • AjaxTimer:95 getData start
  • AjaxTimer:95 getData start
  • AjaxTimer:95 getData start
  • AjaxTimer:98 data=188
  • AjaxTimer:98 data=Vermont
  • AjaxTimer:98 data=88
  • AjaxTimer:98 data=2014-08-26T00:00:00
  • AjaxTimer:83 interval start
  • AjaxTimer:85 interval end
  • AjaxTimer:83 interval start
  • AjaxTimer:85 interval end
  • AjaxTimer:83 interval start
  • AjaxTimer:85 interval end

getData is not called a second time. I'm not sure where I'm going wrong here.

3
  • 2
    getData as a statement by itself does nothing; it's just a reference to the function. You need to actually call the function with some arguments to execute it, as you are in the last 4 lines of your logic. However, making 4 AJAX requests every 5 seconds is not a good pattern to be following. It will not scale well and is in effect DDOS'ing your own server. A better idea would be to firstly return all data from a single endpoint, and also to use Websockets/Server Sent Events to retrieve it. Apr 18, 2019 at 12:46
  • Yes, getData is not being called, but changing it to getData() will call it Apr 18, 2019 at 12:49
  • Rory, thank you for the input - makes total sense. Apr 18, 2019 at 12:52

1 Answer 1

0

Your setInterval is this:

    window.setInterval(function () {
        console.log("interval start"); // Log to console
        getData;                       // A variable
        console.log("interval end");   // Log to console
    }, 5000);

All function calls in JavaScript must end with (), so just update the middle line to

        getData();

and getData will be called by the interval.

2
  • 1
    It'll be called, but with no arguments. Apr 18, 2019 at 12:48
  • Sure, but that's near to the original source. Adding arguments is possible, of course.
    – Sebastian
    Apr 18, 2019 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.