0

I have trouble with timer in button click. When i click button startpause() method is called there i set start timer and stop timer. It works fine when I click button normally(one click after sometime another click) but when I click the button again and again speedly the timer starts to jump with 2-3 secs. Seems like more than one timer is running.. Anyone have any idea....?? here time is my timer method

function startpause() {

    if(FLAG_CLICK) {
        setTimeout(tim,1000);               
        FLAG_CLICK = false;
    }
    else {
        clearTimeout(ti);
        FLAG_CLICK = true;
    }
}

function tim() { 

    time.innerHTML = t;
    t = t + 1;      
    ti= setTimeout("tim()", 1000);
}
suja
  • 1,198
  • 2
  • 12
  • 32

3 Answers3

0

You need to store setTimeout somewhere in order to manipulate it later.

var myVar;

function myFunction()
{
  myVar=setTimeout(function(){alert("Hello")},3000);
}

function myStopFunction()
{
  clearTimeout(myVar);
}

ref http://www.w3schools.com/js/js_timing.asp

lngs
  • 690
  • 1
  • 8
  • 17
0

Maybe you must change this:

if(FLAG_CLICK) {
    setTimeout(tim,1000);               
    FLAG_CLICK = false;
}

to:

if(FLAG_CLICK) {
    tim();               
    FLAG_CLICK = false;
}

It seems works for me normally

Anton Kucherov
  • 307
  • 1
  • 6
0

Try this:

// assuming you declared ti and t out here, cuz I hope they're not global

var t = 0;
var ti;    
var running = false;

function startpause() {

    clearTimeout(ti);
    if(!running) {
        ti = setTimeout(tim,1000); 
        running = true;
    } else {
        running = false;
    }
}
function tim() { 
    time.innerHTML = t;
    t = t + 1; 
    ti = setTimeout(tim,1000); 
}

You can read more about the .setTimeout() here: https://developer.mozilla.org/en/docs/DOM/window.setTimeout

Also, see the jsfiddle I just created: http://jsfiddle.net/4BMhd/

Amy
  • 7,388
  • 2
  • 20
  • 31
  • yuhooo the concept worked. the code you supplied didnt work. It works only for each start click of timer. but i added to ti = setTimeout('tim()', 1000); in the tim() method that worked.. thank you so much for the idea :-) – suja Mar 08 '13 at 07:06
  • Sorry I was tinkering with it. But one thing is, I recommend not passing the string `'tim()'` into `setTimeout()` because it forces the function to evoke the `eval()` function to interpret that string and execute it as JavaScript. As you know or may not know, **eval is EVIL!** (http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea) – Amy Mar 08 '13 at 07:10