jQuery(document).ready(function($) {
// the loop trick belong to "alertCount": 4 inside the json, changing that
will change the loop counter
var alarmData = {
"alertCount": 3,
"trigger": [{
"id": 47,
"status": "active",
"create_uid": 1,
"create_date": "2018-04-19 01:38:39.59",
"region": null,
"acknowledge_by": "Hashmat",
"write_uid": 1,
"write_date": "2018-04-23 03:35:04.745",
"date": "2018-04-19",
"serial": null,
"sim": null,
"acknowledge_date": "2018-04-19",
"station_id": null,
"station_alerts": 72,
"sound_triggered": null
},
{
"id": 48,
"status": "active",
"create_uid": 1,
"create_date": "2018-04-19 01:38:39.59",
"region": null,
"acknowledge_by": "Hashmat",
"write_uid": 1,
"write_date": "2018-04-23 03:35:04.745",
"date": "2018-04-19",
"serial": null,
"sim": null,
"acknowledge_date": "2018-04-19",
"station_id": null,
"station_alerts": 72,
"sound_triggered": null
},
{
"id": 49,
"status": "active",
"create_uid": 1,
"create_date": "2018-04-19 01:38:39.59",
"region": null,
"acknowledge_by": "Hashmat",
"write_uid": 1,
"write_date": "2018-04-23 03:35:04.745",
"date": "2018-04-19",
"serial": null,
"sim": null,
"acknowledge_date": "2018-04-19",
"station_id": null,
"station_alerts": 72,
"sound_triggered": null
},
{
"id": 50,
"status": "active",
"create_uid": 1,
"create_date": "2018-04-19 01:38:39.59",
"region": null,
"acknowledge_by": "Hashmat",
"write_uid": 1,
"write_date": "2018-04-23 03:35:04.745",
"date": "2018-04-19",
"serial": null,
"sim": null,
"acknowledge_date": "2018-04-19",
"station_id": null,
"station_alerts": 72,
"sound_triggered": null
}
]
};
var audioElements = document.getElementsByTagName('audio');
$.each(alarmData.trigger, function(index, alart_value) {
// update the status
// once the sounds are played (once for each alarm), then update the status
for each alarm triggered
var countAlert = alarmData.alertCount;
if (alart_value.sound_triggered == null || alart_value.sound_triggered ===
false) {
audioElements[index].play(); // play the alert for first time
audioElements[index].onended = function() { // once finished, then play it
according the number of alerts from backend(for jsfiddle purpose we use
local data source)
if (index < --countAlert) {
this.play();
}
};
}
}); // close foreach loop for alertData.trigger
})
JSFIDDLE
https://jsfiddle.net/Hashmat_Waziri/9t0sexo2/