jquery - Having multiple timers Work separately using javascript -
so here question
i trying create timer, , timer created every client created, 1 div (this small chunk of actual code, problem timer)
<div class="timer"> <input src="/images/playbutton.png" type="image" class="btnplay" /> <div class="clock"> <span class="min">00</span> <span class="s">:</span> <span class="sec">00</span> </div>
and here javascript behind timer makes work
$j('.btnplay').click(function () { var clock = $j(this).parent().children('.clock'); function pad(val) { return val > 9 ? val : "0" + val; } timerobject = (function starttimer() { clock.children('.sec').text(pad(++sec % 60)); clock.children('.min').text(pad(parseint(sec / 60, 10))); }); //the 1000(milliseconds) means execute function every 1 second timer = setinterval(timerobject, 1000); }// end of play button if statement
now here main problem code, first timer works fine, reason, when play second timer, time start first timer left off, know there lot of similar questions out there, of people using 2 different divs there timer, forced use one, advice or fix highly appreciated, been stuck on quite long.
the problem using global variables sec
, timer
. fix this, use jquery's .data()
, .removedata()
functions each timer has own set of values.
function pad(val) { return val > 9 ? val : "0" + val; } $j(function($) { $('.btnplay').click(function() { var $timer = $(this).closest('.timer'), $clock = $timer.find('.clock'); $timer.data('sec', 0); if (!$timer.data('interval')) { $timer.data('interval', setinterval(function() { var sec = $timer.data('sec') + 1; $clock.children('.sec').text(pad(sec % 60)); $clock.children('.min').text(pad(math.floor(sec / 60))); $timer.data('sec', sec); }, 1000)); } }); });
in order stop interval timer, use:
clearinterval($timer.data('interval')); $timer.removedata('interval');
note: make more efficient using single interval timers.
you might not care, since setinterval()
not guaranteed called every second, timer not accurate. following more accurate:
$timer.data('start', date.now()); if (!$timer.data('interval')) { $timer.data('interval', setinterval(function() { var sec = math.floor((date.now() - $timer.data('start')) / 1000); $clock.children('.sec').text(pad(sec % 60)); $clock.children('.min').text(pad(math.floor(sec / 60))); }, 1000)); }
Comments
Post a Comment