0

I am still new to javascript and trying to wrap my head around this function I created. I know that javascript executes code asynchronously. However, In the for loop below, I, 1) append my string to a cell in my table 2) if the string is empty or falsey 3) I empty out all the cells and alert the user with a message.

for (var i = 0; i < string.length; i++){
    $('<td>').html(string[i]).appendTo(tr); 
    console.log("These are the params: " + string[i]);
    if(!string[i]) {
        tbody.empty();
        console.log("The string is false returning...");
        alert("You have not setup your rack params yet!");
        return;
    }

}

The problem I am seeing here is, the alert message actually comes before my tbody.empty() call. So I actually see the previous data table first and after I confirm the alert then it empties out the table.

Can someone explain to me how exactly does the order work here, and how can we fix this to empty the table first then send the alert message?

tiger_groove
  • 956
  • 2
  • 17
  • 46
  • 1
    The alert doesn't come before the `.empty()` call, but it does come before the page gets redrawn. So the elements are gone, but you can still see them. –  Mar 14 '18 at 21:41
  • @doodlemeister How can I fix this ? – tiger_groove Mar 14 '18 at 21:42
  • 1
    ...you can put the `alert()` in a short `setTimeout` to give the page a chance to update. `setTimeout(() => alert("The string..."), 15)` –  Mar 14 '18 at 21:42
  • 4
    "*I know that javascript executes code asynchronously.*" - [**NO**](https://stackoverflow.com/questions/2035645/when-is-javascript-synchronous). – Bergi Mar 14 '18 at 21:49

0 Answers0