Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

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 !

— asked March 23rd 2010 by David Dupuis
  • settimeout
  • timer
0 Comments

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);
    
    — answered March 23rd 2010 by Kosso
    permalink
    0 Comments
  • 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);
    
    — answered March 24th 2010 by Glenn Tillemans
    permalink
    0 Comments
  • Does this mean clearTimeout is currently broken?

    — answered March 28th 2010 by salo corgan
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.