search

Home  >  Q&A  >  body text

javascript - Problem with timer in each method

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>each</title>
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>
<body>
    <ul>
        <li class="on">0</li>
        <li class="on">0</li>
        <li class="on">0</li>
        <li class="on">0</li>
        <li class="on">0</li>
        <li class="on">0</li>
        <li class="on">0</li>
        <li class="on">0</li>
    </ul>
<script type="text/javascript">
    var num = 0,
    timer = null;
    $(".on").each(function (index, value) {
        timer = setInterval(function(){
            if (num == 900) {
                clearInterval(timer);
            }else{
                num++;
            }
            $(value).text(num);
        },50)
    })
 
</script>
</body>
</html>

The first question is whether the final appearance obtained by if(num==1000) and if(num==900) is different? When num==900, except for the last one which differs by a few 900, the others are all 900. When it is 1000, can all li become 1000?
The second question is that the function in the timer is written like this, why only the last li stops and the other li cannot stop

    timer = setInterval(function(){
        if (num == 998) {
            clearInterval(timer);
        }
        num++;
        $(value).text(num);
    },50)
为情所困为情所困2753 days ago368

reply all(1)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-18 11:00:13

    timer is used as a global variable, and its reference points to the last bound timer. When clearInterval, only the last bound timer is stopped. The number no longer changes just because num no longer increases. You can Console.log(num) in the timer, you will find that only the last timer has stopped

    As for why 1000 is like this and 900 is not, it’s because 1000/8 is divisible and depends on the number of li elements. It’s just a coincidence and there is no special reason

    reply
    0
  • Cancelreply