Reputation: 1
<script>
//GET THE DATA
$.getJSON('https://api.tfl.gov.uk/line/mode/tube,overground,dlr,tflrail/status', function(data) {
var counter = 1;
console.log(data);
$.each(data, function(index,station) {
$.each(station.lineStatuses, function(index,value2) {
if (counter <= 16) {
if (station.name != 0) {
var stationName = station.name;
var stationStatus = value2.statusSeverityDescription;
var stationStatusReason = value2.reason;
$("#stationStatus").append(
$("<div>")
.addClass("row"));
$("#stationStatus").empty().append(
$("<div/>")
.addClass("stationName col-sm-6")
.append(stationName));
$("#stationStatus").append(
$("<div/>")
.addClass("stationStatus col-sm-6")
.append(stationStatus));
if (stationStatusReason != undefined) {
$("#stationStatus").append(
$("<div/>")
.addClass("stationStatusReason col-sm-12")
.append(stationStatusReason));
}
counter++;
}
}
});
});
});
</script>
I have created some code to retrieve some data using getJSON.
Once I have the data I'm looping through and displaying the contents. My problem is I can display all of the content in one hit fine, but I'd like to add a delay in between each loop so it displays a little bit like a news ticker.
I think I'm nearly there but my code in its current form is only showing the last item in the array. If I step through using devtools it seems to be doing the right thing but I don't know how to add a delay automatically?
I try using setTimeout and similar but it's ignored?
Upvotes: 0
Views: 1172
Reputation: 8617
All the setTimeout are ran at nearly the same instance; As in,
setTimeout(foo(),3000)
setTimeout(foo(),3000)
setTimeout(foo(),3000)
Will then run 3 foo()s all at once, 3 seconds later. In order to get them to run later simply change it to
setTimeout(foo(),3000*0)
setTimeout(foo(),3000*1)
setTimeout(foo(),3000*2)
Then you'll get your functions ran at 0,1,2 seconds.
In the form of your example,
$.getJSON('https://api.tfl.gov.uk/line/mode/tube,overground,dlr,tflrail/status', function(data) {
function readLineStatus(station,lineStatus){
if (counter <= 16) {
if (station.name != 0) {
console.log(station);
console.log(lineStatus);
}
counter++;
console.log('Counter: '+counter);
}
}
function readStation(station,timeout){
return function(){
$.each(station.lineStatuses, function(index,lineStatus) {
readLineStatus(station,lineStatus)
});
};
}
var counter=1;
$.each(data, function(index,station) {
console.log('station index:'+index);
var timeout = 500*index;
setTimeout(readStation(station,timeout), timeout);
});
});
Upvotes: 1