如何在smartface中手动停止setTimeInterval函数?

时间:2015-06-25 08:13:35

标签: smartface.io

我创建了一个如下所示的setInterval方法,我想随时随地停止它。顺便说一句,该函数在if-else语句中,因此我无法访问stop函数。

怎么可能?

var intervalID = setInterval(function () {
            if (flag) {
                stopTimer();
                Pages.Page1.Label1.text = "";
            }
            if (time == 0) {
                stopTimer();
                Pages.Page1.Label1.text = "";
                Device.makeCall(callNumber.rows[0][0]);
            } else
                updateTime();
        }, 1000);

    function updateTime() {
        time = time - 1;
        Pages.Page1.Label1.text = time;
    }

    function stopTimer() {
        clearInterval(intervalID);
    }

1 个答案:

答案 0 :(得分:0)

只需将标志变量设置为true

  

flag = true;

或者,我建议在if / else范围之外声明你的函数。

例如,使用启动/停止方法创建一个计时器实例:

timer =  function() {};

timer.prototype.start = function ()
{
    this.timerId = setInterval(function () {  
        /* ... */
        /* call to doWork here or simply your code */
    }, 1000);
}

timer.prototype.doWork = function ()
{
    // override here if you want and wall doWork in setInterval
}

timer.prototype.stop = function ()
{
     clearInterval(this.timerId);
}

var t = new timer();
// start the timer
t.start();
// stop the timer
t.stop();

这样您可以根据需要处理计时器。