Increase an index to a certain number and then decrease until reset with jquery

Asked

Viewed 397 times

3

How can I make a script in jquery to increase an index to a certain number and then decrease one by one until zero.

I’m doing it the following way to increase but I would like that when it reached the 5 it would decrease until zero.

var index = 0;

setInterval(function ()
{
    teste();

}, 10000, true );

function teste()
{
    index++;
}

2 answers

4


You need a control variable indicating whether to increment or decrement, or to use some modular arithmetic:

Using a control variable:

var index = 0;
var inc = +1;

var handle = setInterval(teste, 10000, true); // como o @bfavaretto indicou!

function teste()
{
    if (index == 5)
        inc = -1;

    index += inc;

    if (index == 0)
        clearInterval(handle);
}
  • True, my (removed) response was bankrupt.

  • Actually, she would be alternating between 4 and 5 at the end... incidentally I had not noticed the function calling another function directly. I’ll improve on that answer!

  • Good solution +1

1

Here’s another idea, using an object to store the value of the index and also direct it; because I didn’t see the question in time and without disrespect to the answer from Miguel Angelo that was already accepted when I put my.

var index = {    // um objeto para guardar ...
    valor: 0,    // o valor inicial e que vai mudar
    direcao: ,   // a direccao, se sobe (1) ou desce (0)
    maximo: 5    // o máximo que pode atingir
};

var contador = setInterval(teste, 10000);

function teste() {
    // usar o valor
    console.log(index.valor);

    index.direcao ? index.valor++ : index.valor--;
    if(index.valor == index.maximo) index.direcao = !index.direcao;
    if (!index.direcao && index.valor < 0) clearInterval(contador);

}

Example

Browser other questions tagged

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