1

I have a code to print a pyramid pattern using callback in javascript.

Right now I am able to load entire code after 2 sec.

I need to print pattern rows after 2 sec interval of time instead loading it at a whole using call back and promises . How can I do it ?

var n = 5;
for (var i = 0; i < n; i++) {
    getStar(i, n).then(star => console.log(star));
}

function getStar(i, n) {
    return new Promise((resolve, reject) => {
        var str = '';
        for (var j = 1; j < n - i; j++) {
            str = str + ' ';
        }
        for (var k = 1; k <= (2 * i + 1); k++) {
            str = str + '*';
        }
        setTimeout(() => {
            resolve(str);
        }, 2000)
    })
}
4
  • You can't use document.write asynchronously. Use document.body.innerHTML += "some content"; Commented Sep 30, 2019 at 6:07
  • @JonasWilms ok , I have changed that , but how can I give timer to each of the loops ? Means printing rows after 1 second ? Also , my question is different. It is not same as duplicate thing Commented Sep 30, 2019 at 6:14
  • Have a look at "delay in a Javascript loop" Commented Sep 30, 2019 at 6:26
  • @JonasWilms I tried , but not getting desired output. Can you edit in this code ? Commented Sep 30, 2019 at 6:37

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.