0

I have the code:

function sleep(ms){
        return new Promise(function(resolve,reject){
            setTimeout(function(){
                resolve();
            },ms)
        });
    }
let str = 'abcdef';
for(let i=0;i<str.length;i++){
   sleep(1000);
   console.log(str[i]);
}

How can I print str[i] each 1 second? This is code example, setInterval don't solve my problem!

norbitrial
  • 12,734
  • 5
  • 20
  • 46

5 Answers5

0

Using ES7, you can wrap your for loop in an async function that waits for the sleep promise to be resolved.

function sleep(ms){
  return new Promise(function(resolve,reject){
setTimeout(resolve, ms)
  });
}
    
let str = 'abcdef';

async function loop(){
  for(let i = 0; i < str.length; i++) {
await sleep(1000);
console.log(str[i]);
  }
}

loop()

Of course, you can make this function more flexible passing the string you want to loop over as argument.

function sleep(ms){
  return new Promise(function(resolve,reject){
setTimeout(resolve, ms)
  });
}
    
async function logSlowly(string){
  for(let i = 0; i < string.length; i++) {
await sleep(1000);
console.log(string[i]);
  }
}

logSlowly('abcdef')
0xc14m1z
  • 3,387
  • 1
  • 12
  • 22
0

    let str = 'abcdef';
    for(let i=0;i<str.length;i++){
       setTimeout(function() {
         console.log(str[i])
    }, 1000 * i)
    }
Cid
  • 13,273
  • 4
  • 22
  • 42
bbz
  • 113
  • 8
0

const str = 'mystring';
const printEveryOneSecond = (s) => {
  for (let i = 0; i < s.length; i++) {
      setTimeout( () =>{
        console.log(s[i])
      }, i * 1000)
    }
}
printEveryOneSecond(str);
Nicolae Maties
  • 1,963
  • 1
  • 8
  • 19
0

I was thinking about the solution what you made. I guess what solves your issue is the following code snippet:

(function () {
   let str = 'abcdef';
   let timing = 0;
   let printCharWithDelay = (character, timing) => {
      setTimeout(function() {
         console.log(character);
      }, timing);
   };
   
   for(let i = 0; i < str.length; i++) {
      printCharWithDelay(str[i], timing);
      timing += 1000;
   }
})();

I have completely restructured your code, if you run it you will have the required result.

Basically the code delays printing the passed character with the calculated milliseconds. Obviously it can be simplified but this is a good example to understand how setTimeout behaves in this scenario.

To read further about window setTimeout() method follow the link here.

norbitrial
  • 12,734
  • 5
  • 20
  • 46
0

Try to call sleep with await in front. Like this:

await sleep(1000);

Please use the search function befor posting duplicates here

To use the rigth functionaly please take a look to the dokumentation at this link here

M.Saad
  • 3
  • 2