Run JavaScript code every second with rAF.js? -
i moved using settimeout requestanimationframe per post at: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
how can set code inside animation() loop execute every second?
i like:
animate() { if(playgame) { requestanimframe(animate); } var time = new date().gettime(); if(time % 1000 <= 10) { // code run ~every second } // need fix this, executes fast, need add score // every 100 milliseconds (player must stay in zone 2 seconds win) if(playerinzone()) { gamescore++; if(gamescore >= 100) { endgame(); } } else { gamescore = 0; } } i'm not sure if calling time , performing modulus right way? in way change gamescore code fire every (for example) 200 milliseconds?
note:
use code @ top of javascript file:
window.requestanimframe = (function(){ return window.requestanimationframe || window.webkitrequestanimationframe || window.mozrequestanimationframe || window.orequestanimationframe || window.msrequestanimationframe || function(/* function */ callback, /* domelement */ element){ window.settimeout(callback, 1000 / 60); }; })(); but i've included raf.js in file, unsure use:
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestanimationframe polyfill erik möller. fixes paul irish , tino zijdel // mit license (function() { var lasttime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestanimationframe; ++x) { window.requestanimationframe = window[vendors[x]+'requestanimationframe']; window.cancelanimationframe = window[vendors[x]+'cancelanimationframe'] || window[vendors[x]+'cancelrequestanimationframe']; } if (!window.requestanimationframe) window.requestanimationframe = function(callback, element) { var currtime = new date().gettime(); var timetocall = math.max(0, 16 - (currtime - lasttime)); var id = window.settimeout(function() { callback(currtime + timetocall); }, timetocall); lasttime = currtime + timetocall; return id; }; if (!window.cancelanimationframe) window.cancelanimationframe = function(id) { cleartimeout(id); }; }());
when requestanimationframe called "current time" sent in milliseconds, this:
var lasttime = 0; animate(currenttime) { if (currenttime >= lasttime + 1000) { // 1 second has passed, run code here lasttime = currenttime; } if(playgame) { requestanimationframe(animate); } }
Comments
Post a Comment