1

I have the function "showElement" that has a setTimeout. How can I make that the calls to the function in the eventListener of the 'btnSend' execute one right after the other one?

I tried with .then() but didn't work.

document.getElementById('btnSend').addEventListener('click', e => {
    e.preventDefault();
    result = validateInputs(email, subject, message);
    if(result) {
        showElement(document.getElementById('formGroupSpinner'), 2000);
        showElement(document.getElementById('formGroupSuccessImg'), 2000);
        resetForm();
    }
});

//expects an html element and a number representing miliseconds. Shows the html element for that amount of time.
function showElement(element, mSeconds) {
    element.classList.remove('d-none');
    element.classList.add('d-block');
    setTimeout( () => {
        element.classList.remove('d-block');
        element.classList.add('d-none');
    }, mSeconds);
}

Both functions execute at the same time.

jo_va
  • 13,504
  • 3
  • 23
  • 47
Floro Varela
  • 69
  • 1
  • 8

5 Answers5

3

There's many different approaches to this but I would suggest using a Promise like this:

document.getElementById('btnSend').addEventListener('click', e => {
    e.preventDefault();
    var result = validateInputs(email, subject, message);
    if(result){
        showElement(document.getElementById('formGroupSpinner'), 2000).then(()=>{
            return showElement(document.getElementById('formGroupSuccessImg'), 2000);
        }).then(()=>{
            resetForm();
        });
    }
});

//expects an html element and a number representing miliseconds. Shows the html element for that amount of time.
function showElement(element, mSeconds) {
    return new Promise((resolve, reject) => {
        element.classList.remove('d-none');
        element.classList.add('d-block');
        setTimeout( () => {
            element.classList.remove('d-block');
            element.classList.add('d-none');
            resolve();
        }, mSeconds);
    });
}

Basically, the function after the .then() only gets executed once you called the resolve();.

Alternatively you could also use a callback or async / await.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Sv443
  • 708
  • 1
  • 7
  • 27
1

you could use a callback to execute other instructions after the function has ended:

//First you add a param "callback" to the function
function showElement(element, mSeconds, callback) {
    element.classList.remove('d-none');
    element.classList.add('d-block');
    setTimeout( () => {
        element.classList.remove('d-block');
        element.classList.add('d-none');
        //Then you ask if the callback function is present and call it
        if(callback && typeof callback === "function") callback();
    }, mSeconds);
}

//Then use it in your event like this:
document.getElementById('btnSend').addEventListener('click', e => {
    e.preventDefault();
    result = validateInputs(email, subject, message);
    if(result) {
        showElement(document.getElementById('formGroupSpinner'), 2000, () => {
            showElement(document.getElementById('formGroupSuccessImg'), 2000);
            resetForm();
        });  
    }
}); 

Fernando Bravo Diaz
  • 551
  • 1
  • 4
  • 11
1

You can do this by using Promise. You have to wrap your showElement() function into a promise and call the promise resolver once setTimeout fires. Then your calling code can pipe your the promises together with then:

showElement(document.getElementById('formGroupSpinner'), 2000).then(() => {
    showElement(document.getElementById('formGroupSuccessImg'), 2000).then(() => {
        resetForm();
    });
});

However, this quickly leads to callback hell.

You can avoid this by using async/await. You mark your function as async, then you can use await within it to wait for the promises to resolve before continuing to the next one:

await showElement(document.getElementById('formGroupSpinner'), 2000);
await showElement(document.getElementById('formGroupSuccessImg'), 2000);
resetForm();

Here is a working demo:

document.getElementById('btnSend').addEventListener('click', async e => {
    e.preventDefault();
    await showElement(document.getElementById('formGroupSpinner'), 2000);
    await showElement(document.getElementById('formGroupSuccessImg'), 2000);
});

function showElement(element, mSeconds) {
  return new Promise((resolve, reject) => {
    element.classList.remove('d-none');
    element.classList.add('d-block');
    setTimeout(() => {
        element.classList.remove('d-block');
        element.classList.add('d-none');
        resolve();
    }, mSeconds);
  });
}
.d-none {
  display: none;
}

.d-block {
  display: block;
}
<button id="btnSend">Send</button>

<div id="formGroupSpinner" class="d-none">Spinner</div>
<div id="formGroupSuccessImg" class="d-none">Success image</div>
jo_va
  • 13,504
  • 3
  • 23
  • 47
  • 1
    Thank you, after trying different approaches, this one worked for me. However I ended up using the solution provided by Bergi – Floro Varela Feb 13 '19 at 14:28
0

The simplest way to do what you want is simply changing the second showElement to 4000 instead of 2000.

That way one will have a timeout of 2 seconds and the other 4 seconds.

0

To make a promise chain, you first have to have a promise.

function showElement(element, mSeconds) {
  return new Promise(function(resolve,reject){
    element.classList.remove('d-none');
    element.classList.add('d-block');
    setTimeout( () => {
      element.classList.remove('d-block');
      element.classList.add('d-none');
      resolve();
    }, mSeconds);
  }
}

Then you can use showElement().then(/*something here */)

Mirakurun
  • 4,859
  • 5
  • 16
  • 32