Home > Software design >  JavaScript - I want to show a modal that indicate user to wait for process to complete
JavaScript - I want to show a modal that indicate user to wait for process to complete

Time:10-31

I am building an app in which some javascript functions take time to complete. The logic is CPU extensive no XHR calls.

During that time I want to show an overlay (Please wait...) which indicate user to wait and also restrict them from pressing further buttons.

In order to test my original code, I prepared a separate snippet to check if some other logic is not creating problems but it has the same behavior.

const btn = document.querySelector('#showModal');
const modal = document.querySelector('.modal');
btn.addEventListener('click', ()=>{
    modal.classList.toggle('is-open');


    // takes about 3 - 4 seconds to complete.
    timeTakingFuction();

    modal.classList.toggle('is-open');
});

I am a beginner in javascript and have a rough idea that wait modal shows up but after function complete.

Please anyone can help me in the right direction.

CodePudding user response:

You can change your markup so that on button click you show the modal and then execute your function timeTakingFuction(). On this function set that after it finish you hide the modal.

Something like that:

const btn = document.querySelector('#showModal');
const modal = document.querySelector('.modal');
btn.addEventListener('click', ()=>{
  modal.classList.toggle('is-open');
  // takes about 3 - 4 seconds to complete.
  timeTakingFuction();

});

function timeTakingFuction() {
// your logic and then ->
  modal.classList.toggle('is-open');
};

Or even something like that:

btn.addEventListener('click', timeTakingFuction);
function timeTakingFuction() {
  modal.classList.toggle('is-open');
// your logic and then ->
  modal.classList.toggle('is-open');
};
  • Related