javascript - Executing code inside setInterval function only once per few seconds -
i'm working on simple project html , javascript; , have problem timer.
i'm calculating seconds between 2 date()
objects; , every 2 seconds, want new random number. have setinterval
runs every 100 ms , when past 2 sec mark, code within if
statement should run.
so question is: how can create sure code execute 1 time per 2 seconds in if
statement within setinterval()
runs every 100 ms?
here code:
var starttime = new date(); var endtime = new date(); var randomnumber = 0; var gametimer = setinterval(function(){ //calculate seconds; var secondspassed = math.round( (endtime - starttime) / 1000 ); if(modulo(secondspassed,2) == 0){ //when "gate" open maintain executing every 100 mili seconds. //but want execute 1 time every 2 seconds. randomnumber = math.floor(math.random()*lanes.length); $(lanes[randomnumber]).append(box); } endtime = new date(); }, 100); var modulo = function (n, m) { var remain = n % m; homecoming math.floor(remain >= 0 ? remain : remain + m); };
i think asking double-interval timer.
class="lang-js prettyprint-override">var interval = 100, beat = 2000, ticks = 0; var timer = setinterval(function(){ runsevery100ms(); // ««« code here runs every 100 ms. if (ticks > 0 && ticks % beat === 0) { runsevery2000ms(); // ««« code here runs every 2000 ms. ticks = 0; } ticks += interval; }, interval);
demo fiddle here.
javascript jquery timer setinterval
No comments:
Post a Comment