Mac Ank
Mac Ank

Reputation: 51

Adding 2 Delays In Javascript Loop

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.

Upvotes: 0

Views: 185

Answers (4)

Ivan Ivanov
Ivan Ivanov

Reputation: 146

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);
    }
}

Upvotes: 4

prasanth
prasanth

Reputation: 22490

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>

Upvotes: 1

Titus
Titus

Reputation: 22474

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.

Upvotes: 2

ANUPAM CHAUDHARY
ANUPAM CHAUDHARY

Reputation: 151

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

Upvotes: 0

Related Questions