javascript - Using while(Date.now() < interval) {} with requestAnimationFrame() -


we know how difficult make proper update algorithm if fps important or this.

anyway, came infinite-ish while cycle hack, freezes program until next frame, , seems work flawlessly.

var = date.now() var fps = 40; var interval = 1000 / fps; function mainloop() {      while (date.now() - < interval) {}  // freezes program until next frame      requestanimationframe(mainloop);      = date.now();      // update logic goes here } mainloop(); 

i haven't seen solution anywhere, wanted ask whether clean , correct. know bad freezing program wait , piece of code looks terrible, seems work. there cleaner solution work code?

you can use settimeout wait time not precise. changing interval time can average delay precise enough.

var starttime = date.now(); var fps = 40; var frames = 0; var interval = 1000 / fps;  function mainloop() {     frames++;     var timeelapsed = date.now() - starttime,         averagefps = 1000 * frames / timeelapsed;     if(averagefps < fps && interval > 0) interval -= 0.1;     if(averagefps > fps) interval += 0.1;     settimeout(mainloop, interval);      // update logic goes here } settimeout(mainloop, interval); 

but there still risk computer isn't able meet requested fps if it's slow.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -