+ 3
How can I make realtime setInterval in JavaScript
I make an animation project with setInterval in JS. When I set interval to 10ms, it was so laggy when I run the code in my phone. So how to fix it?
3 Respuestas
+ 4
The setInterval() method define a delay between end of the callback function execution and its next execution, not between each execution ^^
You cannot be sure of time between two executions, because you cannot know what duration will be needed for the execution: if execution of function has a duration of 100ms, you will never can execute it every 50ms ;P ... but however, you can use Date.now() to time execution duration, and use setTimeout inside the callback function with this time retrieving of the delay to be a little bit more accurate (but you cannot reduce delay under the duration of code execution):
function mycallback() {
var t = Date.now();
/* code to be interval executed */
t = Date.now() - t;
var d = 500; // the expected delay
d = (d>t) ? d-t : 0;
window.setTimeout(mycallback,d);
}
mycallback(); // not necessary to use setTimeout, and anyway avoid of calling it with setInterval, as you will have many instances of self-calling (looping) function...
+ 2
setInterval(function name, 10);
0
@Iwan yes I now how to make it. But when I use setInterval(myFunction, 10) , the code run not real time when i run in my phone.