Javascript: restarting countdown timer doesn't work as I expect it to -
i making countdown timer should reseting , starting anew every 10 seconds. code came now:
function count(){ var end_date = new date().gettime()+10*1000; setinterval(function(){ var current_date = new date().gettime(); var seconds_left = parseint((end_date - current_date) / 1000); document.getelementbyid("countdown").innerhtml = seconds_left + " seconds "; }, 1000); } setinterval(function(){count()}, 10*1000);
it supposed function follows:
+ set interval restart count() every 10 seconds.
+ count() defines end_date - date 10 seconds now.
+ count() sets interval restart every 1 second.
+ every 1 second seconds_left variable changed according how current_date changed respect end_date.
+ seconds_left becomes 0, setinterval step 1 fires , starts count() anew.
which step implementing wrong way? misunderstand functioning of setinterval()? here jsfiddle: http://jsfiddle.net/sy5stjun/ .
my guess each call in own new object , multiple instances of fighting ever 10 seconds.
using approach using date objects here possible re-write:
var tmr = null; var time; function biginterval() { clearinterval(tmr); time = (new date()).valueof() + (10 * 1000); smallinterval(); tmr = setinterval(smallinterval, 500); } function smallinterval() { var cur = (new date()).valueof(); var seconds_left = parseint((time - cur) / 1000); document.getelementbyid("countdown").innerhtml = seconds_left + " seconds"; } biginterval(); setinterval(biginterval, 10*1000);
in above code i've updated small timer 500ms instead of 1000ms won't line system clock @ 1000 , visual jumps in numbers.
if exact timing isn't 100% important here possible shorter method:
var t = 10; setinterval(function() { document.getelementbyid("countdown").innerhtml = t + " seconds"; t--; if (t <= 0) { t = 10; } }, 1000);
Comments
Post a Comment