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.
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.getData
is not being called, but changing it togetData()
will call it