Stephen F
Stephen F

Reputation: 43

setInterval keeps stacking even with clearInterval

I'm making a simple punch in / punch out timer.

Problem im facing is that it works perfectly on page load but when the user clicks end_work_btn then begin_work_btn, the timer kinda stacks the initial value and the new one starting from 0 so it's trying to display both. It keeps stacking everytime they click the buttons until page reload when it resets.

I've done a bunch of reading and figured clearInterval(timer) would do it but no go so assuming i'm not using it correctly or i'm way off the ball on whats wrong here.

Here's what I got so far

<button id="begin_work_btn">Begin Work</button>
<button id="end_work_btn"><span id="hours"></span>:<span id="minutes"></span>:<span id="seconds"></span></button>

<script>
var emp_id = '2';
var timer = null;

function reset_timer(time){
    var sec = time;
    clearInterval(timer);

    function pad ( val ) { 
        return val > 9 ? val : "0" + val; 
    }

    var timer = setInterval( function(){
        $("#seconds").html(pad(++sec%60));
        $("#minutes").html(pad(parseInt(sec/60,10)%60));
        $("#hours").html(pad(parseInt(sec/3600,10)));
    }, 1000);
}

reset_timer(<?php echo $existing_time;?>);

$("#begin_work_btn").click(function(){

    $.ajax({
        type: "post",
        url: "<?php echo $url;?>process.php",
        data: "agent_id="+emp_id+"&action=begin_work",
        success: function(data){
            var sec = 0;
            reset_timer(sec);
            $('#begin_work_btn').hide();
            $('#end_work_btn').show();
        }
    });
});

$("#end_work_btn").click(function(){

    $.ajax({
        type: "post",
        url: "<?php echo $url;?>process.php",
        data: "agent_id="+emp_id+"&action=end_work",
        success: function(data){
            $('#end_work_btn').hide();
            $('#begin_work_btn').show();
        }
    });
});

</script>

Upvotes: 1

Views: 327

Answers (1)

epascarello
epascarello

Reputation: 207511

Pretty simple, scope is different. In your code you have two variables named timer. The one inside the function is created each time reset_timer is called. One outside never gets a value. So each time you call the function, another instance of timer is created.

var timer = null; //<-- outside 

function reset_timer(time){
    clearInterval(timer);
    var timer = setInterval( ... , 1000); //<--redefined inside so each time, it creates new variable
}

You basically have this:

function reset_timer(time){
    var timer;
    clearInterval(timer);
    timer = setInterval( ... , 1000);
}

It should not be defined with var. This way it updates the variable defined outside of the function each time it is called.

var timer = null; 

function reset_timer(time){
    if (timer) clearInterval(timer);
    timer = setInterval( ... , 1000); //<--no more var
}

Upvotes: 3

Related Questions