-1

Hello I have a problem in Javascript.

I need that when clicking on a button in HTML, that the values 0 to 10 appear on the document, and I want each value to be displayed with a dash before, but especially 500ms between each among them.

For this I use the for loops and the SetTimeout function.

I'll let you read the code.

            let button = document.querySelector("button");
            let p = document.querySelector('p');

            button.addEventListener('click', () => {
                for (let i = 0; i<=10; i++) {
                        setTimeout(()=>{
                            document.write(`- ${i} <br>`);
                        },500) 
                }
            })
    <button type="button">Clic</button>

But the values are showing up in the same time at once, and not one by one.

Pac0
  • 21,465
  • 8
  • 65
  • 74
Zaka_dev
  • 55
  • 4

1 Answers1

0

Since setTimeout is an asynchronous function, you've to increase the delay in each iteration

    let button = document.querySelector("button");
    let p = document.querySelector('p');

    button.addEventListener('click', () => {
        for (let i = 0; i<=10; i++) {
                setTimeout(()=>{
                    document.write(`- ${i} <br>`);
                },500 * i) 
        }
    })
Lyes
  • 400
  • 5
  • 19