javascript - Problem with timer in each method
为情所困
为情所困 2017-05-18 10:58:13
0
1
379
<!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)
为情所困
为情所困

reply all(1)
我想大声告诉你

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template