如何停止计时器.在原生脚本中使用点击事件或离开页面设置interval

How to stop timer.setinterval with a tap event or leaving page in nativescript

本文关键字:事件 离开 interval 页面设置 计时器 何停止 原生 脚本      更新时间:2023-09-26

我有一个计数器,当加载页面时开始加载,当time == 0触发对话框并导航到另一个页面时停止加载。但我也想在用户点击按钮或放弃并离开页面时停止它。

下面是我的代码,用于启动计时器并在时间=== 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);   */
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);
}

在JS文件的声明式UI XML中:

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

我也建议在你的timer.clearInterval(countId)函数验证countId是否仍然有效;并在清除间隔后使其无效;这样你就不会有任何奇怪的情况