html - Simple JavaScript timer -
i trying create simple javascript count down timer, have problem when displaying "minute" string "0" when has 1 digit, adds "0" every second while "seconds" not add more "0", 1 "0" when displays 1 numerical digit, how display 1 "0" minute?
regards.
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>count down test</title> </head> <body> <p id="demo"></p> <script> var seconds = 10; //10 sec test, 60 var minutes = 5; //10 min test, 59 var hour = 1; //can set 48 hours 2days, 72 hours 3days //function display time function count() { if(hour == 0 && minutes == 0 && seconds == 0) { clearinterval(); } //reset seconds when reached 0 if(seconds == 0) { seconds = 10; //originally 60 minutes--; } if(minutes == 0) { minutes = 10; //originally 59 if(hour != 0) { hour--; } } //-1sec every second seconds--; //if less 10 sec add "string" character 0 first digit if(seconds < 10) { seconds = "0" + seconds; } //if less 10 min add "string" character 0 first digit if(minutes < 10) { minutes = "0" + minutes; } document.getelementbyid("demo").innerhtml = hour + " : " + minutes + " : " + seconds; } count(); setinterval(function(){ count(); }, 1000); </script> </body> </html>
when minute digit less 10 adding string "0" orignal data type number minute , converting string type , getting repeated thats why adding 0 again , again string have parsefloat() orignal minute numeric type js not add 0 string again each second.. hope make sense can check code below test again.
//you doing //wrong case
//if less 10 sec add "string" character 0 first digit if(seconds < 10) { seconds = "0" + seconds; } //if less 10 min add "string" character 0 first digit if(minutes < 10) { minutes = "0" + minutes; } // // right case //if less 10 sec add "string" character 0 first digit if(seconds < 10) { seconds = "0" + seconds; } //if less 10 min add "string" character 0 first digit if(minutes < 10) { minutes = "0" + parsefloat(minutes); }
Comments
Post a Comment