最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - increase value until limit then decrease loop - Stack Overflow

programmeradmin4浏览0评论

I try to increase the value of a variable valuem from 0 to 10 and if the value of valuem is 10 it should decrease until the value is 0, then again increase until 10 and so on.

for example: 0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1 0 1 2 ...

what is the simplest and efficientest way to do that?

var valuem = 0;
$('#number').text(valuem);

function count() {
    valuem++;
    $('#number').text(valuem);

    if (valuem == 10) {
        valuem--;
        $('#number').text(valuem);
    }

}

setInterval(count, 1000);

I try to increase the value of a variable valuem from 0 to 10 and if the value of valuem is 10 it should decrease until the value is 0, then again increase until 10 and so on.

for example: 0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1 0 1 2 ...

what is the simplest and efficientest way to do that?

var valuem = 0;
$('#number').text(valuem);

function count() {
    valuem++;
    $('#number').text(valuem);

    if (valuem == 10) {
        valuem--;
        $('#number').text(valuem);
    }

}

setInterval(count, 1000);
Share Improve this question edited Apr 24, 2016 at 12:44 Tamas Hegedus 30k12 gold badges66 silver badges101 bronze badges asked Apr 24, 2016 at 12:41 klamertdklamertd 1033 silver badges16 bronze badges 1
  • 1 Check this demo – Tushar Commented Apr 24, 2016 at 12:49
Add a ment  | 

2 Answers 2

Reset to default 7

This way:

var valuem = 0, dir = 1;
$('#number').text(valuem);

function count() {
  valuem += dir;
  $('#number').text(valuem);
  if (valuem < 1) dir = 1;
  if (valuem > 9) dir = -1;
}

setInterval(count, 1000);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="number"></div>

You have to store the counting direction as the part of the state besides the current number to know in which direction to count when valuem is between 1 and 9.

I suppose one might simplify it more by just using the remainder with an offset. This way the entire calculation is done in a single line without any if statements.

var n = 0;
setInterval(function() {
  number.innerHTML = 10 - Math.abs(n++ % 20 - 10);
}, 500);
<h1 id="number"></h1>

发布评论

评论列表(0)

  1. 暂无评论