如何通过点击事件或在本机脚本中保留页面来停止timer.setinterval [英] How to stop timer.setinterval with a tap event or leaving page in nativescript
问题描述
我有一个计数器,该计数器在加载页面时启动,在时间== 0触发时停止,并触发对话框并导航到另一页面.但是我也想在用户点击按钮或他放弃并离开页面时停止它.
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.
下面是我的代码,用于启动计时器并在时间=== 0时结束计时器
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); */
推荐答案
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中:
In your Declarative UI XML for the JS file:
<Page navigatingFrom="onNavigatingFrom">
<Button tap="onButtonTap" text="Click Me"/>
</Page>
我也建议您 使用timer.clearInterval(countId)函数可以验证countId仍然有效;清除间隔后使之无效;这样,您就不会再有任何奇怪的情况了.
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.
这篇关于如何通过点击事件或在本机脚本中保留页面来停止timer.setinterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!