-7

for (var i = 0; i <= 5000; i++) {
  if(i % 5 == 0){
    setTimeout(function() {
        console.log(i);
    }, 5000);
  }
  else{
    console.log(i);
  }
}

I want that once it reaches to number 5 then wait 5 seconds before displaying number 6 in the console. How can I achieve this?

num8er
  • 18,604
  • 3
  • 43
  • 57
  • 3
    Possible duplicate of [How to stop a setTimeout loop?](https://stackoverflow.com/questions/8443151/how-to-stop-a-settimeout-loop) – Mihai T Jul 16 '18 at 11:07

3 Answers3

2

I hope You meant this:

it console.log's non divideable to 5 numbers and then waits 5 second and goes again.

const wait = ms => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

const URL = [...Array(5000).keys()].map(n => n * 2);
const serial = [...Array(5000).keys()].map(n => n * 10);

(async (URL, serial) => {
  for (let i = 1; i <= 5000; i++) {
    if (i % 5 === 0) {
      await wait(5000);
      
      const url = 'http://localhost:3000/?URL='+URL[i]+'&serial='+serial[i];
      console.log('Opening url:', url);
      window.open(url, '_blank');

      continue;
    }

    await wait(500);
    console.log(i);
  }
})(URL, serial);
num8er
  • 18,604
  • 3
  • 43
  • 57
  • I changed code lil bit now it not working.const wait = ms => { return new Promise((resolve) => { setTimeout(resolve, ms); }); } (async () => { $.each(serial, function(index, val) { if (index % 5 === 0) { window.open("http://localhost:3000/?URL="+URL[index]+"&serial="+serial[index], '_blank'); await wait(5000); continue; } await wait(500); window.open("http://localhost:3000/?URL="+URL[index]+"&serial="+serial[index], '_blank'); } })(); – Shah Rushabh Jul 16 '18 at 11:18
  • I hope You wanted to open url where url and serial arrays has modulus of 5 eq 0 – num8er Jul 16 '18 at 11:29
0

javascript is single thread, try not using blocking as it will freeze your entire program.

SetTimeout and recursion can do the job for you

function print(i,total) {
  if (i >= total) {
    return;
  }
  else if (i % 5 === 0) {
    setTimeout(function(){
      console.log(i);
      return print(i+1,total);
    },5000)
  } else {
    console.log(i);
    return print(i+1, total);
  }
}

print(1,100)
user3003238
  • 1,517
  • 10
  • 17
0
function st(i1) {
    setTimeout(function () {
        console.log(i1)

    },5000)
}
function aa(st) {
    return new Promise((resolve => {
       for(var i=1;i<=10;i++){
           if(i==5){
               console.log(i)
               i=i+1;
               resolve(st(i))
               break;
           }
           console.log(i)


       }
    }))
}
async function bb() {
    var ss=await aa(st)
}
bb()