I am trying to display one element at a time. They come from a JSON file. I am using JQuery and setInterval. But the images should change based on the file's "Milliseconds'
What am I doing wrong? my implementation is based on Only display one array item at a time (Javascript)
JSON FILE
{
"Name": "2",
"PlaylistItems": [
{
"FileName": "ad1.png",
"Duration": "00:00:23",
"Milliseconds": 1300.0
},
{
"FileName": "ad2.jpg",
"Duration": "00:00:00",
"Milliseconds": 25000.0
},
{
"FileName": "ad3.png",
"Duration": "00:00:00",
"Milliseconds": 5400.0
}
]
}
Javascript
function DisplayMessages() {
$.getJSON(screenSettingsUrl, (data) => {
if (data != null) {
var i = 0;
setInterval(() => {
divName.css("background-image", "url(./media/" + data.PlaylistItems[i].FileName + ")");
divName.css("background-repeat", "no-repeat");
i++;
if(i == data.PlaylistItems.length) i = 0;
}, data.PlaylistItems[i].Milliseconds);
}
});
}
DisplayMessages();
Any help much appreciated.
Because you have different Milliseconds values setInterval is not the best choice. In this case i would suggest setTimeout and a recursive approach.
var data = { "Name": "2", "PlaylistItems": [ { "FileName": "ad1.png", "Duration": "00:00:23", "Milliseconds": 1300.0 }, { "FileName": "ad2.jpg", "Duration": "00:00:00", "Milliseconds": 2500.0 }, { "FileName": "ad3.png", "Duration": "00:00:00", "Milliseconds": 5400.0 } ] }; function DisplayMessages(i) { setTimeout(() => { console.log(data.PlaylistItems[i].FileName); i++; if (i < data.PlaylistItems.length) DisplayMessages(i); }, data.PlaylistItems[i].Milliseconds); } DisplayMessages(0);
I would suggest using timeouts to perform a recursive loop on your array.
function DisplayMessages() { $.getJSON(screenSettingsUrl, (data) => { var i = 0; if (data != null) { function displayNextItem () { //show the current image divName.css("background-image", "url(./media/" + data.PlaylistItems[i].FileName + ")"); divName.css("background-repeat", "no-repeat"); //advance i to the next image, or back to 0 if it reaches the end //of the array i = ++i % data.PlaylistItems.length; //start the loop for the next element, with it's timeout setTimeout(displayNextImage, data.PlaylistItems[i].Milliseconds); } //start the loop on the first element, with it's timeout setTimeout(displayNextImage, data.PlaylistItems[i].Milliseconds); } }); } DisplayMessages();
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.