Reputation: 143
I believe that it involves setinterval
I've got the second using this
var s=today.getSeconds();
Then using setinterval
I've got this
setInterval(function(){ alert("Hello"); }, 3000);
The question... I don't think I can divide a second by 60 and use that "asynchronously" I think I'm using that word right, a seconds unit divided 60 times, every 1/60th increment something happens
I'm wondering if I should / have to use milliseconds as those units exist, I'd probably just use a ratio or something to make the equivalent of a second / sixty
Upvotes: 1
Views: 3611
Reputation: 10992
var time = 1000/60;
setInterval(function(){ alert("Hello"); }, time);
1000 is milliseconds divided by 60.
But there is a downfall with this approach, if your function doesn't have time to run in that time (a very short timespan) it will not wait until it's finished. So it can have quite disastrous effects on your application.
Then it's probably better to call setTimeout recursively so it will finish executing your function before it's called again.
var time = 1000/60;
(function loop(){
setTimeout(function(){
// logic here
// recurse
loop();
}, time);
})();
Sure requestAnimationFrame is nice but it's not supported on older browsers. If you want working code in older browsers I would advise using a recursive settTimeout approach. That will work everywhere!
Upvotes: 1
Reputation: 41368
As suggested in a comment, since you ask for 60 times per second, it might mean you want to update an animation i.e. change the color, position, shape etc. of some DOM elements on the screen.
For this it's recommended to use
requestAnimationFrame
instead of setInterval
.
So instead of
setInterval(function () {
doSomething();
}, 16)
use
function myFunction () {
doSomething();
requestAnimationFrame(myFunction);
}
requestAnimationFrame(myFunction);
This allows browser to perform certain optimizations.
From MDN:
You should call this method whenever you're ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.
The callback rate may be reduced to a lower rate when running in background tabs.
The name requestAnimationFrame
might be a bit confusing, but you should read it as "please run my callback
whenever the browser is ready to do a repaint of the screen", i.e. you let the browser decide the exact timing instead of imposing it yourself.
Upvotes: 6
Reputation: 66693
One sixtieth of a second is approximately 16 milliseconds, so you can do:
setInterval(function(){ alert("Hello"); }, 16);
Upvotes: 0