mardi 20 octobre 2020

How to give instant user feedback on slow checkbox listeners in JavaScript?

I have a checkbox with a listener attached that executes synchronous code that takes several seconds to complete. The checkbox only shows its updated state (checked or unchecked) after the operation is complete. This confuses users, who think the click didn't register and then click twice, which triggers the operation an additional time.

How can I get the user to see the change in checked state immediately?

const checkbox = document.getElementById("checkbox");
const label = document.getElementById("label");
checkbox.addEventListener("change",()=>
{
 for(let i=0;i<2_000_000_000;i++) {const j=i;} // long running synchronous operation
 label.innerText+=" clicked";
});
<input type="checkbox" id="checkbox">
<label for="checkbox" id="label">Click me</span>

Tested on Firefox Developer Edition 82.0b5.




Aucun commentaire:

Enregistrer un commentaire