0

I'm new to Javascript, I got this Javascript timer from the net. I'm trying to stop the timer and insert the stopped time into the database if a certain PHP variable is set, but I'm not sure how to stop the timer. Here's the code. I saw this post and sadly, I still can't get it to work. How to stop a timer function from running? Thanks!

<script type="text/javascript">
/**********************************************************************************************
* CountUp script by Praveen Lobo (http://PraveenLobo.com/techblog/javascript-countup-timer/)
* This notice MUST stay intact(in both JS file and SCRIPT tag) for legal use.
* http://praveenlobo.com/blog/disclaimer/
**********************************************************************************************/
function CountUp(initDate, id){
    this.beginDate = new Date(initDate);
    this.countainer = document.getElementById(id);
    this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
    this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
    this.hours = 0, this.minutes = 0, this.seconds = 0;
    this.updateNumOfDays();
    this.updateCounter();
}



CountUp.prototype.updateNumOfDays=function(){
    var dateNow = new Date();
    var currYear = dateNow.getFullYear();
    if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
        this.numOfDays[1] = 29;
    }
    var self = this;
    setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));
}

CountUp.prototype.datePartDiff=function(then, now, MAX){
    var diff = now - then - this.borrowed;
    this.borrowed = 0;
    if ( diff > -1 ) return diff;
    this.borrowed = 1;
    return (MAX + diff);
}

CountUp.prototype.calculate=function(){
    var currDate = new Date();
    var prevDate = this.beginDate;
    this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
    this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
    this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
    this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
    this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
    this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}

CountUp.prototype.addLeadingZero=function(value){
    return value < 10 ? ("0" + value) : value;
}

CountUp.prototype.formatTime=function(){
    this.seconds = this.addLeadingZero(this.seconds);
    this.minutes = this.addLeadingZero(this.minutes);
    this.hours = this.addLeadingZero(this.hours);
}

CountUp.prototype.updateCounter=function(){
    this.calculate();
    this.formatTime();
    this.countainer.innerHTML =
        " <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
        " <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
        " <strong>" + this.seconds + "</strong> <small>" + "</small>";
    var self = this;
    setTimeout(function(){self.updateCounter();}, 1000);
}
<?php if(isset($results['calltime'])) {$timevar= date("M d, Y H:i:s",strtotime($results['calltime']));}?> 
window.onload=function(){ new CountUp('<?php echo $timevar; ?>', 'counter'); }

//I need a function to stop timer if (isset($results['firstcall_time']))


</script>
Community
  • 1
  • 1
Belgarion
  • 149
  • 2
  • 3
  • 12

4 Answers4

0

In your method updateCounter() You have following statement

setTimeout(function(){self.updateCounter();}, 1000);

make it like following first.

myTimer = setTimeout(function(){self.updateCounter();}, 1000);

and then whenever you want to stop the timer call this method.

clearTimeout(myTimer);

and then record the time. It uses setTimeout for counting so you have to use clearTimeout for stopping the contdown.

reffer Clear Timeout

Cheers

K D
  • 5,889
  • 1
  • 23
  • 35
0

In the lines:

setTimeout(function(){self.updateNumOfDays();}, (new Date((currYear+1), 1, 2) - dateNow));

And

setTimeout(function(){self.updateCounter();}, 1000);

You can see the recursion is being used, thus the timer keeps running.

So when you want to stop the timer do SOMETHING like this:

 var flag = true;
<?php if (isset($results['firstcall_time'])){ ?>
  flag = false;
<?php } ?>

And modify your script a little bit as:

 setTimeout(function(){if(flag){self.updateNumOfDays();}else{//write code to cleartimeout}}, (new Date((currYear+1), 1, 2) - dateNow));//check for the flag before recursion

And

setTimeout(function(){if(flag){self.updateCounter();}}else{//write code to cleartimeout}, 1000);
Gaurav Pandey
  • 2,798
  • 4
  • 28
  • 41
  • Start without writing the code in the else part... and make sure you put the var flag in the top of the script. – Gaurav Pandey Feb 21 '13 at 13:14
  • Leave it like that only.. No need to write the code to clearTimeout for now. it should work fine as it is. If it doesn't work, leave a message here. – Gaurav Pandey Feb 21 '13 at 13:35
0

He isn't using a timer. He is using setTimeout, but the executing function, is the same method, sort-of like recursion (but strictly speaking, it isn't). So, it's on going. Hope this makes sense.

A timer is implemented like:

// Start
var timerId = setInterval(func() {
    // your code to execute
}, 5000);

// Stop
clearInterval(timerId);

I've added a stop method to CountUp. So you should now be able to do this:

// Start
var counter = new CountUp(new Date(), 'div');

// Stop
counter.stop();

Here's the code. I've just hand coded in here, so if there are any typos or something doesn't work then post a comment.

function CountUp(initDate, id){
    this.beginDate = new Date(initDate);
    this.countainer = document.getElementById(id);
    this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
    this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
    this.hours = 0, this.minutes = 0, this.seconds = 0;

    this.daysTimerId = setInterval(this.updateNumOfDays(), this.getDaysTimerInterval());
    this.updateTimerId = setInterval(this.updateCounter(), 1000);
}

CountUp.prototype.stop=function(){
    clearInterval(this.daysTimerId);
    clearInterval(this.updateTimerId);
}

CountUp.prototype.getDaysTimerInterval=function(dt){
    var dateNow = dt || new Date();
    return (new Date((dateNow.getFullYear()+1), 1, 2) - dateNow));
}

CountUp.prototype.updateNumOfDays=function(){
    var dateNow = new Date();
    var currYear = dateNow.getFullYear();
    if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
        this.numOfDays[1] = 29;
    }
//    var self = this;
//    setTimeout(function(){self.updateNumOfDays();}, self.getDaysTimerInterval(dateNow));
}

CountUp.prototype.datePartDiff=function(then, now, MAX){
    var diff = now - then - this.borrowed;
    this.borrowed = 0;
    if ( diff > -1 ) return diff;
    this.borrowed = 1;
    return (MAX + diff);
}

CountUp.prototype.calculate=function(){
    var currDate = new Date();
    var prevDate = this.beginDate;
    this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
    this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
    this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
    this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()]);
    this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
    this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}

CountUp.prototype.addLeadingZero=function(value){
    return value < 10 ? ("0" + value) : value;
}

CountUp.prototype.formatTime=function(){
    this.seconds = this.addLeadingZero(this.seconds);
    this.minutes = this.addLeadingZero(this.minutes);
    this.hours = this.addLeadingZero(this.hours);
}

CountUp.prototype.updateCounter=function(){
    this.calculate();
    this.formatTime();
    this.countainer.innerHTML =
        " <strong>" + this.hours + "</strong> <small>" + (this.hours == 1? ":" : ":") + "</small>" +
        " <strong>" + this.minutes + "</strong> <small>" + (this.minutes == 1? ":" : ":") + "</small>" +
        " <strong>" + this.seconds + "</strong> <small>" + "</small>";
//    var self = this;
//    setTimeout(function(){self.updateCounter();}, 1000);
}
Mark Graham
  • 171
  • 6
0

Here is how I stopped the counter:

I inserted this few lines before "CountUp.prototype.updateCounter=function(){"

var today=new Date(); 
var start=new Date(2013,10,25,5,35,0); //example: Stop date
diff =  start-today;

Then, inside updateCounter function, instead of directly call the setTimeout I added a condition:

 if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) )  { //on the fly (page is laready open with the counter running) or onload 
    //Time's up!
    } else {
        setTimeout(function(){self.updateCounter();}, 1000);
    }

So the new code will look like this:

var today=new Date(); 
var start=new Date(2013,10,25,5,35,0); 
diff =  start-today; 

Counter.prototype.updateCounter=function(){
this.calculate();
this.formatTime();
this.countainer.innerHTML = " <strong>" + this.seconds + "</strong> " + (this.seconds == 1? ":" : ":")+
    " <strong>" + this.minutes + "</strong> " + (this.minutes == 1? ":" : ":")+
    " <strong>" + this.hours + "</strong> " + (this.hours == 1? ":" : ":")+
    " <strong>" + this.days + "</strong> " + (this.days == 1? ":" : "");
var self = this;
if ( ( (this.seconds==0) && (this.minutes==0) (this.hours==0) && (this.days==0) ) || (diff <=0) )  { //on the fly or onload 
//Time's up!
} else {
setTimeout(function(){self.updateCounter();}, 1000);
}
}

Hope that will help.

Shams

Shams Larbi
  • 151
  • 2
  • 5