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

3

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

I'm doing the following to increase but I'd like it to drop to zero by the time it gets to # 5.

var index = 0;

setInterval(function ()
{
    teste();

}, 10000, true );

function teste()
{
    index++;
}
    
asked by anonymous 08.04.2014 / 21:44

2 answers

4

You need a control variable indicating whether it is to increment or decrement, or 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);
}
    
08.04.2014 / 21:56
1

Here's another idea, using an object to store the value of the index and also the direction; because I did not see the question in time and without deference to the reply from Miguel Angelo that was already accepted when I placed mine .

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

    
09.04.2014 / 00:40