How to stop timer.setinterval with a tap event or

2019-09-05 17:33发布

问题:

I have an counter that loads when starts when a page is loaded and stops when the time == 0 fires a dialog and navigates to another page. But i also want to stop it when the use taps a button or when he gives up and leave the page.

Below is my code for starting the timer and ending it when the time === 0

var timeKeep = vm.time;
var count = 0;

countId = timer.setInterval(() => {
    timeCountDown();
    count += 1;
    if (count === timeKeep) {
        timer.clearInterval(countId);
        dialogs.alert({
            message: "Time Up!",
            okButtonText: "OK"
        });
        aemnavigation.goResults(vm.correct);
    }
}, 1000);   */

回答1:

var timeKeep = vm.time;
var count = 0;

var countId = timer.setInterval(() => {
    timeCountDown();
    count += 1;
    if (count === timeKeep) {
        timer.clearInterval(countId);
        dialogs.alert({
            message: "Time Up!",
            okButtonText: "OK"
        });
        aemnavigation.goResults(vm.correct);
    }
}, 1000);  


exports.onButtonTap = function() {
  timer.clearInterval(countId);
  /** Do whatever else you need to **/
}

exports.onNavigatingFrom = function() {
  timer.clearInterval(countId);
}

In your Declarative UI XML for the JS file:

<Page navigatingFrom="onNavigatingFrom">
  <Button tap="onButtonTap" text="Click Me"/>
</Page>

I would also recommend in your timer.clearInterval(countId) function you verify that countId is still valid; and invalidate it after you clear the interval; that way you don't have any weird corner cases.