I am trying to better understand the use of deferred objects in jQuery.
The getData
method below fetches some data asynchronously. When done, it should be displayed to some predefined ( log
) section by addToChart
. This should happen periodically, hence my using setInterval
inside getData
's done
handler.
function getData() {
return $.ajax({
url: 'https://demo-live-data.highcharts.com/time-data.csv',
type: 'GET'
});
}
getData().done(addToChart, function() {
setInterval(getData, 1000);
});
function addToChart(data) {
document.getElementById('log').innerText += data;
}
$(document).ready(function() {
getData();
});
In above code, getData
seems to get called only once. How do I let it be called periodically?
Also, is there any way to actually debug this code, rather than run it and scratch my head why it doesn't behave as expected? (I'm new to JavaSCript, in case you wonder). I stepped through the code using the Firefox debugger but that didn't help.
You would need to do a while loop :
while (condition) {
code block to be executed
}
or the do/while loop :
do {
code block to be executed
}
while (condition);
setTimeout is used to delay a function https://www.w3schools.com/jsref/met_win_settimeout.asp
What you want to use is setInterval https://www.w3schools.com/jsref/met_win_setinterval.asp
So looking at what you're trying to do, i would do it like this:
$(document).ready(function() {
function getData() {
$.ajax({
url: 'https://demo-live-data.highcharts.com/time-data.csv',
type: 'GET'
}).done(addToChart);
}
function addToChart(data) {
document.getElementById('log').innerText += data;
}
setInterval(getData, 1000);
});
Move the done
inside the function so it will get called every time the function does and request succeeds
function getData() {
return $.ajax({
url: 'https://demo-live-data.highcharts.com/time-data.csv',
type: 'GET'
})
.then(addToChart)
.always(function() {
setTimeout(getData, 1000);
});
}
Alternate approach is wrap what you are currently doing in a new function
function getData() {
return $.ajax({
url: 'https://demo-live-data.highcharts.com/time-data.csv',
type: 'GET'
});
}
function loadChart() {
getData()
.then(addToChart)
.always(function() {
setTimeout(loadChart, 1000);
});
}
loadChart()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.