Javascript: Multiple timers VS single timer -


i have simple question javascript timers , performance bugs me because can't figure out right way it.

here problem: have special timing function self corrects itself:

function setcorrectinginterval(func, delay) {     if (!(this instanceof setcorrectinginterval)) {         return new setcorrectinginterval(func, delay);     }     var target = date.now() + delay;     var self = this;     function tick() {         if (self.stopped) {             return;         }         target += delay;         func();         settimeout(tick, target - date.now());     }     settimeout(tick, delay); } 

then, in application use function n times set n different timer variables. if have 2 timer variables use function twice set them. in code bellow execute first task every 1000ms , second task every 2000ms:

var firsttimer,     secondtimer;  function startfirsttimer() {     firsttimer = setcorrectinginterval(function() {         console.log("first!");     }, 1000); }  function startsecondtimer() {     secondtimer = setcorrectinginterval(function() {         console.log("second!");     }, 2000); }  startfirsttimer(); startsecondtimer(); 

in angular application need multiple timing events grows , grows. (tempoprary) solution create new timer variables new settimeouts using setcorrectinginterval function mentioned above.

so got thinking - wouldn't better (performance wise) have 1 single timer variable 1 single settimeout in using if statements execute tasks meet condition, this:

var timer;  function starttimer() {     var counter = 1;     timer = setcorrectinginterval(function() {         console.log("first!");         if (counter % 2 === 0) {             console.log("second!");         }          counter++;     }, 1000); }  starttimer(); 

( provided every tasks repeat execution delay multiple of 1000 )

which approach better , why? explanation appreciated, thank you


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -