+ 2
Canvas Performance
Hi there I'm currently working on a simple game using HTML canvas. Well, I'm having a little bit o trouble with serinterval () because the time I give to the function doesn't seem to be right. I mean, it says 500 milliseconds but it is actually 700/800. What can I do? Do you have any suggestions? Thanks
6 Antworten
+ 4
Don't use setInterval for canvas timer, use requestAnimationFrame instead.
+ 2
I use requestAnimationFrame to the game itself
I use setInterval to create enemies every x seconds, x-=50 for example.
But the value ain't realistic
+ 2
I don't know what actually is delaying setInterval for you but to me it seems exactly 500 milliseconds.
var arr=[];
let time=setInterval(()=>{
var a=new Date();
console.log(a.getMilliseconds());
arr.push(a.getMilliseconds());
if(arr.length>=20){
clearInterval(time);
console.log(arr);
}
},500);
+ 1
look at the use of request animation frame in this code of r8w9 and discussion in comments
https://code.sololearn.com/WA2a15a13a16/?ref=app
+ 1
Thank you
+ 1
It is a problem with JS concurrency model.
According to MDN,
"Basically, the setTimeout needs to wait for all the code for queued messages to complete even though you specified a particular time limit for your setTimeout."
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
As others have pointed out, it is better to use requestAnimationFrame when performance is important.