node.js - Time based javascript functions with setInterval -
i'm using node.js question strictly javascript related. i'm interfacing i2c board fade lights , i'd fade them @ specific rate, 1 second. setinterval, in theory should work like... if wanted fade them 100 steps in 1 second like...
var fader = setinterval(function(){ //will fade light 100 steps in 1 second dofade(something,something); },10)
but depending on code inside of interval loop, may take longer 1 second (i tested , application 2.5 seconds). i'm sure fact function dofade taking set amount of time happen causing issue i'm curious if there real way make happen within 1 second.
the closest you'll ever get, afaik, relying entirely on js this:
var fader = (function(now) { var timeleft, end = + 1000,//aim 1000 ms stepsremaining = 100, callback = function() {//define here, avoid redefining function objects dosomething(foo, bar); setter(); }, setter = function() {//recompute interval, set anew if (stepsremaining <= 0) {//avoid infinite timeouts return; } timeleft = (end - (+(new date))); timeleft= timeleft > 0 ? timeleft : 0;//ensure positive timeleft, if not, 0 intervals ==> asap fader = setinterval( callback, math.floor( timeleft/stepsremaining-- ) ); }; setter(); return fader; }(+(new date)));//get ms
this code, though untested creates function objects beforehand. then, using setter
, everytime interval finishes, long haven't set 100 intervals, new interval computed. after work done, callback
function, setter
called again. here, number of remaining steps checked, timeleft computed again , based on remaining steps, decremented 1 on each call setter
.
avoid setting intervals long, or using float-numbers, i'm calling math.floor
, , avoid setting negative timeout values, i'm checking value of timeleft
, too, obviously
Comments
Post a Comment