简体   繁体   中英

setInterval Javascript MVC2

I am trying to use setInterval to calculate time left, here is my script:

 var intervalID;
        function StartTimer() {
            var intervalID = setInterval(function () {
                var settimmer = 100; //  $('#timeleft').val();
                var seconds = 0;
                seconds++;
                if (seconds >= 60) {
                    settimmer--;
                    seconds = 0;
                    $('#timeleft').val(settimmer);
                }
            }, 1000);
        }
        function StopTimer() {
            clearInterval(intervalID);
        }

<input type="text" size="8" id="timeleft" name="timeleft" value="100" />
    <button onclick="StartTimer();">
        start</button>
    <button onclick="StopTimer();">
        Stop</button>

I does not work, however when I use the following script, it works but don't know how to stop it:

  var settimmer = 100;
   var seconds = 0;
    $(function () {

            window.setInterval(function () {
                seconds++;
                if (seconds >= 60) {
                    settimmer--;
                    seconds = 0;
                    $('#timeleft').val(settimmer);
                }

            }, 1000);

    });

Thanks in advance.

您在StartTimer()函数中重新声明intervalID ,然后删除var

The problem is the scope of variable. You re-declaring intervalID in the function StartTimer, and it will cover the global variable 'intervalID' and only be used in this function. In fact, the variable 'intervalID' outside is not valued. So when you use clearInterval(intervalID), it certainly does not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM