Looping Javascript timer -
i trying run sequential countdown timers can't figure out how wait timer finish before moving onto next item.
for(var = 0; < 5; i++) { var count = 5; var counter = setinterval(timer, 1000); } function timer() { count--; if (count <= 0) { $('.workout-timer').text(count + "secs"); clearinterval(counter); return; } $('.workout-timer').text(count + "secs"); }
this goes negative, without loop code counts down 5 0 fine. question how several countdowns 1 after another? timer not right way go it?
you this:
function startcountdown(count, delay, callback) { if (!count) { callback && callback(); return; } //do here console.log(count); settimeout(function () { startcountdown(--count, delay, callback); }, delay); } startcountdown(5, 1000, function () { startcountdown(5, 1500); });
however can messy if have lot of nested callbacks, here's 1 out of many approach use deal issue:
var queue = [ { count: 5, delay: 1000 }, { count: 10, delay: 200 }, { count: 5, delay: 5000 } ]; processnextcountdown(); function processnextcountdown() { var options = queue.shift(); if (options) { startcountdown(options.count, options.delay, processnextcountdown); } }
Comments
Post a Comment