+ 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

4th Feb 2021, 10:45 PM
Alexandre
Alexandre - avatar
6 Antworten
+ 4
Don't use setInterval for canvas timer, use requestAnimationFrame instead.
4th Feb 2021, 11:05 PM
Calviղ
Calviղ - avatar
+ 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
4th Feb 2021, 11:14 PM
Alexandre
Alexandre - avatar
+ 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);
4th Feb 2021, 11:46 PM
Abhay
Abhay - avatar
+ 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
5th Feb 2021, 7:42 AM
bell
bell - avatar
+ 1
Thank you
5th Feb 2021, 11:02 AM
Alexandre
Alexandre - avatar
+ 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.
6th Feb 2021, 6:45 AM
Ore
Ore - avatar