How to stop setTimeInterval function manually in smartface?

104 Views Asked by At

I create a setInterval method like below, I want to stop it anytime from anywhere. By the way, that function is in a if-else statement, so I cannot access the stop function.

How can it be possible?

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

There are 1 best solutions below

0
On

Just set the flag variable to true.

flag = true;

Alternatively, i would suggest to declare your functions outside of the if / else scope .

For instance, create a timer instance with start / stop methods as such :

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();

This way you can handle your timer as you want.