Reputation: 322
I am new to javascript. I am checking a time period from my database and showing how much time left to the end of the period.
I got the time value with strtotime
as a variable $lefttime
in php. My problem is with javascript part so i am not writing the php codes.
So my javascript code is:
var s = <?php echo $lefttime; ?>; //s stands for seconds
var d = Math.floor(s/60); //d stands for minutes
s -= d*60;
var count = setInterval(functime, 1000);
function functime() {
s--;
if(s < 0) {
d--;
s = 59;
var san = s;
var dak = "0" + d;
}
else if(d < 0 ) {
clearInterval(functime);
document.getElementById('id').innerHTML = "over";
}
else if(d < 10){
var dak = "0" + d;
if(s < 10) {
var san = "0" + s;
}
else {
var san = s;
}
}
else if(s < 10){
var san = "0" + s;
if(d < 10) {
var dak = "0" + d;
}
else {
var dak = d;
}
}
else {
var san = s;
var dak = d;
}
document.getElementById('id').innerHTML = dak+":"+san;
}
I create dak
and san
variables to check if the value is a digit, if so add 0
to the left of them.
So it works perfect except stopping when d < 0
. It counts down till 00:00
and then shows
0-1:59
, and then undefined:undefined
.
Please help me I can't find what is wrong.
Upvotes: 0
Views: 1856
Reputation: 5981
setInterval returns an identifier for the interval
var myInterval = setInterval(functime, 1000);
And it's this numeric identifier that should be passed as a parameter to clearInterval
clearInterval(myInterval);
update: You code is much too complex. You have too many nested if/else, so it makes it complicated to understand. You should create several simple functions to isolate small chunks of code with a specific responsibility. By example:
var s = <?php echo $lefttime; ?>; //s stands for seconds
var d = Math.floor(s/60); //d stands for minutes
s -= d * 60;
update(d, s);
if(d >= 0) {
var myInterval = setInterval(functime, 1000);
}
else {
finish();
}
function functime() {
s--;
if(s < 0 ) {
d--;
if (d < 0 ) {
clearInterval(myInterval);
finish();
return;
}
else {
s = 59;
}
}
update(d, s);
}
function format(value) {
if(value < 10) {
return '0' + value;
}
return value;
}
function update(d, s) {
var san = format(s);
var dak = format(d);
document.getElementById('id').innerHTML = dak + ":" + san;
}
function finish() {
document.getElementById('id').innerHTML = "over";
}
Upvotes: 3