html - starting 1 timer clock after another and looping it using javascript -
i have 2 count-down timers in website. 1 timer start automatically, next 1 should start after 1st completed. should loop on forever, i.e. starting 1 clock after another.
here code tried:
function count() { var starttime = document.getelementbyid('hms').innerhtml; var pieces = starttime.split(":"); var time = new date(); time.sethours(pieces[0]); time.setminutes(pieces[1]); time.setseconds(pieces[2]); var timedif = new date(time.valueof() - 1000); var newtime = timedif.totimestring().split(" ")[0]; document.getelementbyid('hms').innerhtml = newtime; if (newtime !== '00:00:00') { settimeout(count, 1000); } else { count1(); } } count(); function count1() { var starttime = document.getelementbyid('hms1').innerhtml; var pieces = starttime.split(":"); var time = new date(); time.sethours(); time.setminutes(pieces[1]); time.setseconds(pieces[2]); var timedif = new date(time.valueof() - 1000); var newtime = timedif.totimestring().split(" ")[0]; document.getelementbyid('hms1').innerhtml = newtime; if (newtime !== '00:00:00') { settimeout(count, 1000); } else { count(); } }
html:
<div id="hms">00:00:10</div> <div id="hms1">00:02:10</div>
i unable make work. help!!
your current code there - couple of small issues:
time.sethours
missing parameter on line 23, should follows:var time = new date(); time.sethours(pieces[0]);
line 30 should call alternate function:
settimeout(count1, 1000);
only 1 counter should running @ time, no need last line (
count1()
).
here's updated jsbin.
however, dry solution here more appropriate avoid having manage 2 functions:
var currenttimer = 'hms'; var alternatetimer = 'hms1'; function count() { var timer = document.getelementbyid(currenttimer); var starttime = timer.innerhtml; var pieces = starttime.split(':'); var time = new date(); time.sethours(pieces[0]); time.setminutes(pieces[1]); time.setseconds(pieces[2]); var timedif = new date(time.valueof() - 1000); var newtime = timedif.totimestring().split(' ')[0]; // update dom timer.innerhtml = newtime; if(newtime === '00:00:00') { // swap 2 timers currenttimer = [alternatetimer, alternatetimer = currenttimer][0]; } settimeout(count, 1000); } count();
hope helps!
Comments
Post a Comment