Unable to stop timer (setTimeout)
Hello,
I have got a problem with the setTimeout function used in a recursive context. I'm unable to stop the timer with the clearTimeout command…
Here is the code :
var myTimer = 0;
var myCount = 0;
var label = Titanium.UI.createLabel({
top:0,
left:100,
width:50,
height:30,
text:'0',
color:'#999',
font:{fontSize:12, fontWeight:'bold'},
backgroundColor:'#fff'
});
win.add(label);
var _start = Titanium.UI.createButton({
top:0,
left:150,
title:'Start',
width:50,
height:30,
color:'#000',
textAlign:'center',
font:{fontSize:12, fontWeight:'bold'}
});
win.add(_start);
var _stop = Titanium.UI.createButton({
top:0,
left:200,
title:'Stop',
width:50,
height:30,
color:'#000',
textAlign:'center',
font:{fontSize:12, fontWeight:'bold'}
});
win.add(_stop);
function increase()
{
label.text = ++myCount;
myTimer = setTimeout(increase, 1000);
}
function stopCounter()
{
clearTimeout(myTimer);
}
_start.addEventListener("click", function(e){
increase()
});
_stop.addEventListener("click", function(e){
stopCounter()
});
Thanks for help !
3 Answers
-
Hi,
Try using setInterval an clearInterval
var i = setInterval(function() { Ti.API.info('my app is busy doing things every second ... '); },1000); // then use this to stop/clear it. clearInterval(i);
-
Like Kosso said, use the setInterval and clearInterval propperty. here is an example what i've been using for timed stuff:
t=0; timer = setInterval(function() { t++; Ti.API.info(t); if(t==10) { // do something; clearInterval(timer); } },1000);
-
Does this mean clearTimeout is currently broken?