2
\$\begingroup\$

I'm doing a clock in javascript and I am not sure this way is the best way to rotate the pointers.

Is this ok, or is there a better way?

// browser vendors var browsers = [ 'webkit', 'Moz', 'ms', 'O', '']; // function to move the pointers function moveMe(el, unit) { var deg = unit * 360 / 60; browsers.each(function (b) { el.style[b + 'Transform'] = 'rotate(' + deg + 'deg)'; }); } // function to check the time function checkTime() { var date = new Date(); var seconds = date.getSeconds(); var minutes = date.getMinutes(); var hours = date.getHours(); moveMe(sPointer, seconds); !seconds && moveMe(mPointer, minutes); !minutes && moveMe(hPointer, hours); } 

The fiddle I'm playing with is here.

\$\endgroup\$

    2 Answers 2

    2
    \$\begingroup\$

    First of all, your code use Array.each() method, which is a non-standard Javascript method, added by Mootools. I would rather use a standard loop, in order to keep a vanilla JS code.

    Then, instead of setting all properties every time, you should test which properties are supported by the browser and set them accordingly.

    Finally, since you are moving minutes only when !seconds (i.e. seconds == 0), the clock initialization is a bit weird. On page load, you should always move minutes and hours.

    \$\endgroup\$
    4
    • \$\begingroup\$Thanks for feedback! I do initialization on my fiddle. About the .each() I have more mootools but sure, a vanilla loop is better. Good idea to detect browser... About the rotation itself, is that the best way to do it? By setting style on the image?\$\endgroup\$
      – Rikard
      CommentedJan 11, 2014 at 18:46
    • \$\begingroup\$That's indeed the most straightforward solution. Otherwise, you'll need to use HTML5 Canvas API.\$\endgroup\$CommentedJan 11, 2014 at 18:50
    • \$\begingroup\$For reference, there is an Array.forEach() method that is standard JavaScript (ES 5.1).\$\endgroup\$CommentedJan 12, 2014 at 6:51
    • \$\begingroup\$I disagree with the .each comment. If you're using a framework you can write code for the framework\$\endgroup\$
      – megawac
      CommentedFeb 8, 2014 at 23:35
    1
    \$\begingroup\$

    In GCC, if you write !seconds && moveMe(mPointer, minutes); and compile with -Wall you get this warning:

    [Warning] value computed is not used [-Wunused-value] 

    I know this is not C, but the problem is the same and I can't see why you don't explicitly write if.

    \$\endgroup\$
    1
    • \$\begingroup\$+1 for pointing out a possible bug. Is this also the case if the first value is not negated with !? Because this is a common practise in javascript\$\endgroup\$
      – Rikard
      CommentedJan 13, 2014 at 22:34

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.