So, I have this code that is supposed to loop through each record in a table and change the save icon to a checkmark for 2 seconds before changing it back. However, it's not working as expected.
I've used a similar method for other buttons which has worked fine. I suspect it might have something to do with the speed at which the loop processes each record, even though setTimeout should be asynchronous...
Is there a more efficient way to achieve this? I want each button to behave independently without resorting to writing a function that changes all icons at once.
const iconToggle = () => {
const isCheckIcon = btn.firstElementChild.classList.contains('fa-check');
if (isCheckIcon) {
btn.innerHTML = '<i class="fa fa-save fa-2x"></i>';
} else {
btn.innerHTML = '<i class="fa fa-check fa-2x"></i>';
}
}
for (row = 0; row < table.rows.length; row++) {
currentRow = table.rows.item(row);
...
returncode = save_row();
btn = currentRow.getElementsByClassName('record-save')[0].firstElementChild;
if (returncode == 0) {
iconToggle();
setTimeout(iconToggle, 2000);
}
}
EDIT:
$('.table-save-all').on('click', 'i', function() {
var table = document.getElementById('edit_history_table_body');
const iconToggle = (abtn, state) => {
if (state == "save") {
abtn.innerHTML = '<i class="fa fa-save fa-2x"></i>';
} else if (state == "check") {
abtn.innerHTML = '<i class="fa fa-check fa-2x"></i>';
}
}
var currentRow, key, TotalNoBreakDec, OvertimeDec, TotalDec, StartDec, HourSchedule, returncode, btn;
// loop through each row of the table.
for (row = 0; row < table.rows.length; row++) {
currentRow = table.rows.item(row);
...
returncode = save_row();
btn = currentRow.getElementsByClassName('record-save')[0].firstElementChild;
if (returncode == 0) {
iconToggle(btn, "check");
setTimeout(() => { iconToggle(btn, "save") }, 2000);
}
}
btn = document.getElementsByClassName('table-save-all')[0].firstElementChild;
iconToggle(btn, "check");
setTimeout(() => { iconToggle(btn, "save") }, 2000);
});