简体   繁体   中英

Javascript - Best way to implement loading spinner

New to web-development and trying wrap my head around handling the DOM. Want to implement a spinner that appears while data is being processed and disappears after. I figure the order should be something like this

  1. on button press, make spinner visible and call data function
  2. after data function is finished make spinner invisible again

Using Bootstrap 5

Current implementation is something along these lines:

document.getElementById("button").addEventListener("click",function(){document.getElementById("spinner").classList.toggle("invisible");})
document.getElementById("button").addEventListener("click",dataProcess());
document.getElementById("button").addEventListener("click",function(){document.getElementById("spinner").classList.toggle("invisible");})

I understand the order in which event listeners are added are the order they are executed in but the spinner doesn't toggle at because the DOM doesn't update until all the functions are executed(since it toggled twice by then it's just invisible again). Is there a way to update the DOM between events or a better way to implement the spinner altogether?

document.getElementById("button").addEventListener("click",()=>{
    setTimeOut(()=>{
        document.getElementById("spinner").classList.toggle("invisible")
    },600)
    dataProcess();
    document.getElementById("spinner").classList.toggle("invisible")
});

Give a callback function to dataprocess function and make button invisible

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM