0

I am building a javascript function that displays a popup 10 times each time for 5 seconds.

Inside my code I have something like this:

for (i=0; step < 10; i++) 
{
  showPopup();
  //need to add 5 second delay here
  hidePopup();
  //need to add a 5 second delay again
}

I have tried settimeout funcion but am not able to syncronize the delays.

I would appreciate anyone helping me to complete this.

4 Answers 4

4

You can utilize await inside your loop to wait for a Promise that resolve after 5 seconds to create delays.

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function main() {
    for (let i = 0; i < 10; i++) {
        showPopup();
        await delay(5000);
        hidePopup();
        await delay(5000);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use setTimeout and to synchronise the delays use the iteration's index, here is an example:

for (i=0; i < 10; i++) {
  setTimeout(showPopup, (i * 2) * 500);
  setTimeout(hidePopup, ((i * 2) + 1) * 500);
}

function showPopup() {
  console.log("@popup show");
}

function hidePopup() {
  console.log("@popup hide");
}

In this example, I've set the delay to 500 milliseconds instead of 5 seconds so you won't have to wait too long to see the effect.

Comments

1

You could do with setInterval for repeat the loop ever 5 second and use settimeout for display time of the data

var interval = '';

var count = 1; //count for check 10 times

function show() {
  if (count <= 10) {
    interval = setInterval(() => {
      count++;
      el.style.display = 'block'
      clearInterval(interval)
      setTimeout(hide, 5000)
    }, 5000);
  }
}
var el = document.querySelector('p');


function hide() {
  el.style.display = 'none';
  show()
}
show()
p {
  display: none
}
<p>hello</p>

Comments

0

Use SetInterval instead of loop and then stop the setInterval using clearInterval

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.