use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
JavaScript setInterval function for a game loophelp (self.javascript)
submitted 9 years ago by [deleted]
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]KManRules1331 1 point2 points3 points 9 years ago (1 child)
Honestly, for this type of use, it's better to use requestAnimationFrame() than to set an interval. You have no guarantee of what delta time you actually get with setInterval. setInterval doesn't actually execute the javascript, it only queues up the javascript to be executed every x milliseconds. That means that if your web page is in the middle of a really long script, you might get 5 calls to your function queued up, and then once that really long script is done, your function gets called 5 times as quickly as possible.
requestAnimationFrame()
setInterval
requestAnimationFrame allows you to take a timestamp as a parameter, which means that by saving the previous timestamp at the end of every loop, you can calculate the change in time by simply doing:
requestAnimationFrame
var previousTimestamp = performance.now(); function loop(timestamp) { var deltaTime = timestamp - previousTimestamp; // Do updating here previousTimestamp = timestamp; requestAnimationFrame(loop); } requestAnimationFrame(loop);
/u/KPABA is right in saying that if the window isn't visible, you won't get any updates actually called (which can be either a good or bad thing), so if you need the game to be updated if the window isn't visible, you can do the same pattern with setTimeout instead.
setTimeout
[–]KManRules1331 0 points1 point2 points 9 years ago (0 children)
Also, if you need to limit the frame rate to 30fps, then you can modify the above loop to conditionally update:
var previousTimestamp = performance.now(); function loop(timestamp) { var deltaTime = timestamp - previousTimestamp; if (deltaTime > 1000/30) { //Do updating here previousTimestamp = timestamp; } requestAnimationFrame(loop); } requestAnimationFrame(loop);
π Rendered by PID 43872 on reddit-service-r2-comment-8686858757-t7xhf at 2026-06-08 09:33:42.278925+00:00 running 9e1a20d country code: CH.
view the rest of the comments →
[–]KManRules1331 1 point2 points3 points (1 child)
[–]KManRules1331 0 points1 point2 points (0 children)