2013-09-06 3 views
1

Я хочу считать от 3 до 0, а затем обратно до 3 в цикле. Это своего рода «слайдер». Все работает нормально, пока не достигнет clearInterval от counterry. Что мне не хватает?подсчет и обратный отсчет

var counttx = 0, // counter 
    counterrx = setInterval(timerrx, 1000), // countup - start 
    counterry; // countdown after reach 3 

function timerrx(){ 
    counttx = counttx+1; 
    //console.log(counttx); 
    if(counttx > 2){ 
     counterry = setInterval(timerry, 1000); 
     clearInterval(counterrx); 
    } 
} 

function timerry(){ 
    counttx = counttx-1; 
    //console.log(counttx); 
    if(counttx < 2){ 
     setInterval(timerrx, 1000); 
     clearInterval(counterry); 
    } 
} 

ответ

5

Используйте один цикл:

var counttx = 0, countup = true; 

function timerr() 
{ 
    if (countup) 
    { 
    ++counttx; 
    if (counttx >= 3) 
     countup = false; 
    } 
    else 
    { 
    --counttx; 
    if (counttx <= 0) 
     countup = true; 
    } 
} 

setInterval(timerr, 1000); 

Рабочий пример: http://codepen.io/paulroub/pen/weuxk

+0

намного лучше, чем мой ответ lol .... + 1! –

+0

в первый раз, когда я пытался сделать как единую петлю –

+0

как заработал, отлично работает +1! –

1

Базовая логика может выглядеть как ниже, и вы можете настроить это для таймеров интервала в JavaScript.

int counter=0; 
int delta=1; 
bool finished=false; 
while(!finished) 
{ 
    counter+=delta; 
    if(counter==3) 
    { 
     delta=-1; 
    } 
    if(counter==0) 
    { 
     delta=1; 
    } 
    if(condition to end loop is met) 
    { 
     finished=true; 
    } 

} 
Смежные вопросы