How can I make realtime setInterval in JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

3rd Aug 2017, 2:11 PM
Muhammad Bagus Zulmi
Muhammad Bagus Zulmi - avatar
3 Answers
+ 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...
3rd Aug 2017, 6:01 PM
visph
visph - avatar
+ 2
setInterval(function name, 10);
3rd Aug 2017, 2:45 PM
Iwan
Iwan - avatar
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.
3rd Aug 2017, 2:50 PM
Muhammad Bagus Zulmi
Muhammad Bagus Zulmi - avatar