How do I create a time interval in the execution of a for?

Asked

Viewed 84 times

-2

How I create a 1 second interval in the execution of the for or of function?

JavaScript:

function Linha1() {
            for (var i1 = 0; i1 <= 3; i1++, Linha1.setInterval(1000)) {
                if (notas1[0][i1] == 1) {
                    C_Teclado.play();
                } else if (notas1[i1][0] == 2) {
                    CS_Teclado.play();
                } else if (notas1[i1][0] == 3) {
                    D_Teclado.play();
                } else if (notas1[i1][0] == 4) {
                    _Teclado.play();
                } else if (notas1[i1][0] == 5) {
                    E_Teclado.play();
                } else {
                    SomVazio.play();
                }

            }
        }

2 answers

1

To "delay" the execution of something, just involve what you want to delay with setTimeout and determine the time in milliseconds. As in the example:

setTimeout(function Linha1() {
                for (var i1 = 0; i1 <= 3; i1++, Linha1.setInterval(1000)) {
                    if (notas1[0][i1] == 1) {
                        C_Teclado.play();
                    } else if (notas1[i1][0] == 2) {
                        CS_Teclado.play();
                    } else if (notas1[i1][0] == 3) {
                        D_Teclado.play();
                    } else if (notas1[i1][0] == 4) {
                        _Teclado.play();
                    } else if (notas1[i1][0] == 5) {
                        E_Teclado.play();
                    } else {
                        SomVazio.play();
                    }

                }
            }, 1000
          )
  • The problem is that I would like to 'delay' the interval between the for executions and not the Function execution

-1

You can replace your for a setInterval if the range is always the same size, your code would be:

setTimeout(function Linha1() {
    let i = 0

    let interval = setInterval(function () {
        if (i > 3) return clearInterval(interval)

        if (notas1[0][i1] == 1) {
            C_Teclado.play();
        } else if (notas1[i1][0] == 2) {
            CS_Teclado.play();
        } else if (notas1[i1][0] == 3) {
            D_Teclado.play();
        } else if (notas1[i1][0] == 4) {
            _Teclado.play();
        } else if (notas1[i1][0] == 5) {
            E_Teclado.play();
        } else {
            SomVazio.play();
        }

        i++
    }, 1000)
}, 1000)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.