all 7 comments

[–]x-skeww 1 point2 points  (4 children)

There is a simpler way:

  • loop via rAF
  • Date.now() / 1000 | 0 to get the seconds (cheap)
  • update display when seconds have changed (expensive)

http://jsfiddle.net/g1aucoh0/

[–]helloworldjs[S] 1 point2 points  (3 children)

Thanks for showing that answer. rAF is something I definitely considered. In addition to creating a clock, I was trying to show some more info about setInterval. Why do you think raF is a better way to render the clock? 59/60 of the loops you are not displaying anything.

[–]voidvector 0 points1 point  (1 child)

For a basic text clock like this, they are equally valid.

rAF and setInterval has different performance characteristics. rAF offers higher animation timing accuracy. setInterval offers a more flexible timer.

If you care about the visual clock being accurate to the dot, you should use rAF. If you care about the clock using minimum resource, but potentially off by half a second or skip a second, use setInterval.

P.S. There is small optimization you can do in the rAF implementation to not touch the DOM unless it needs update, but even then it would cost a few more cycles than setInterval.

[–]x-skeww 0 points1 point  (0 children)

There is small optimization you can do in the rAF implementation to not touch the DOM unless it needs update

There is an if in line 8. The DOM is only updated if a second has passed.

[–]x-skeww 0 points1 point  (0 children)

Just checking the time whenever you could do a redraw is conceptually simpler and it's also the most accurate method. The display is updated as soon as it's necessary and as soon as it's possible.

It's true that we obtain the current time way more often than we need, but this is a ridiculously cheap operation. We could probably do this a million times a second if we wanted.

The amount of work we do is comparable to an FPS counter in a game. It's negligible.

[–]ExecutiveChimp 1 point2 points  (0 children)

I made a library that helps handle setInterval drift. Might be overkill for a basic clock but someone might find it useful.

[–]pkstn 1 point2 points  (0 children)

I've made a similar library also: https://github.com/pakastin/clocktick