Using three.js to create a rotating analog clock in Javascript

I currently have a traditional clock displayed in my setting that I want to synchronize with the current time. I am able to keep the clock running by calculating each hand's rotation every second, but I am encountering peculiar issues with the minute and hour hands.

hourHand = scene.getObjectByName('Box001');
minuteHand = scene.getObjectByName('Box002');
secondHand = scene.getObjectByName('Cylinder002');

var d = new Date();

var mins = d.getMinutes();
var secs = d.getSeconds();
var hours = d.getHours();

minuteHand.rotateY((-mins / 60) * (2 * Math.PI));
secondHand.rotateY(((mins /60) + (-secs / 3600)) * (2 * Math.PI));
hourHand.rotateY(((-hours / 12) + (mins / 720)) * (2 * Math.PI));


setInterval(function(){
    minuteHand.rotateY((2 * Math.PI) / -3600);
    secondHand.rotateY((2 * Math.PI) / -60);
    hourHand.rotateY((2 * Math.PI) / (-3600 * 12));
},1000);

The challenges I'm facing include:

  • When it is 4:30, the hour hand points directly at 4 instead of being positioned between the 4 and 5; the same issue occurs with the minute hand.
  • I am uncertain about the accuracy of my mathematical calculations since I am observing some unexpected anomalies over time which are difficult to identify.

Is there a more precise method to achieve this synchronization?

Answer №1

There is no guarantee that your interval will fire every 1000ms, leading to accumulated error over time due to the inability to catch up with previous delays.

I suggest basing the hand rotation on a function that uses the current time as input. This way, it doesn't matter when your interval, trigger, or callback executes; whenever it does, it will display the correct result.

The math involved is not overly complex - a clock has 360 degrees. For instance:

(Date.now()/1000)%60 * 6 would give you the second hand rotation in degrees (assuming 0° is at the top).

Similarly, (Date.now()/60000)%60 * 6 would provide the minute rotation, and

(Date.now()/3600000)%24 * 15 for the hour hand rotation. Update: Adjusted the formula for a 24-hour rotation. For a standard clock, with a 12-hour rotation, this should be:

(Date.now()/3600000)%12 * 30

These calculations should be taken with caution as I have not verified them thoroughly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoiding default action on keyboard tab event resets cursor position while typing consecutively

Issue with cursor position resetting to start when tab is the last key pressed I am working on a chrome extension for Gmail using React and need to customize the behavior of the tab key. I have found that using preventDefault and stopImmediatePropagation ...

Error occurs when running Visual Studio Code locally - variable not defined

After successfully going through a Microsoft online demo on setting up an httpTrigger in Visual Studio Code with JavaScript to upload it to Azure Functions, I decided to customize the code for a specific calculation. I managed to get the calculation done a ...

Having trouble viewing a dynamically adjusting Angular NVD3 graph embedded in bootstrap

I have been utilizing the NVD3 library along with bootstrap 3.0 for my project. I have two divs with the classes "col-md-6 col-sm-12" positioned side by side. My goal is to showcase charts in both of these divs. To ensure that the charts are displayed corr ...

Is there a crucial step overlooked in the process of creating an SVG for importing into Three.JS in order to fully capture the essence of the original SVG design

After creating an SVG in Illustrator with multiple stroked paths on separate layers that are unconnected from start to finish and with no fill applied, combining them into a single layer results in the SVG rendering differently in Three.JS compared to the ...

After encountering a character with CSS, begin a new line

I have a CSV spreadsheet with data that looks like this: <p>Features:• first feature• second feature• third feature• fourth feature• and so on (the total number of features is variable)</p> I want each feature to display on a new li ...

When utilizing auth0, an error occurs during the grunt build process

I successfully developed a small project using AngularJS on my local machine without encountering any issues. However, when I attempted to build the project with Grunt, everything stopped working and an error occurred: vendor.ce3c01a3.js:2 Error: [$inject ...

Using external URLs with added tracking parameters in Ionic 2

I am looking to create a unique http link to an external URL, extracted from my JSON data, within the detail pages of my app. Currently, I have the inappbrowser plugin installed that functions with a static URL directing to apple.com. However, I would lik ...

Transforming an ES6 JSON object into a dictionary: a step-by-step guide

As someone who is new to learning ES6 and JQuery, please forgive me if this question has been asked before (I couldn't find similar ones). Currently, I am working on retrieving data from a JSON file in the following format: { EUR: { code: "EUR" ...

The error message "TypeError: window.Razorpay is not a constructor" indicates that

I am attempting to integrate RazorPay into my React app, but I am encountering the following error: https://i.stack.imgur.com/iFvdz.png Here is the code snippet: import TshirtImg from "./tshirt.jpg"; // import Razorpay from 'razorpay' ...

Retrieving data from an AJAX dialog with the use of jQuery and ASP.NET

After spending more than a day on this and reading countless posts on the topic, I am still unable to make it work. My goal is to retrieve a value from a textbox (starting with a textbox for testing) in a javascript pop-up in asp.net using js / ajax. Below ...

Guide on integrating an HTML and CSS register form in Django

I have successfully created a responsive register and login using HTML and CSS. Instead of utilizing the standard register form and login provided by Django upon configuration, I want to apply my own custom template. To summarize, while I am familiar with ...

Linking a Kendo widget to an HtmlHelper component through JavaScript in MVC/Razor

I am currently working on integrating an MVC ListBoxFor control with a Kendo MultiSelectFor to bind and update data. The goal is to have a list of users in the ListBox, and a list of available users in the MultiSelect box. When users are selected from the ...

Using Three.js to apply multiple images onto a sphere and have individual control over each one

I have a 3D sphere that I am looking to map an array of images onto. I want to be able to control each image independently, allowing for fading in and out of each image. To better illustrate my goal, I will provide an example image of what I am trying to a ...

How can I retrieve properties from a superclass in Typescript/Phaser?

Within my parent class, I have inherited from Phaser.GameObjects.Container. This parent class contains a property called InformationPanel which is of a custom class. The container also has multiple children of type Container. I am attempting to access the ...

When creating routes in Express 4.* using node.js, it is essential to use the root directory

Completely new to the world of node.js, I find myself navigating through an outdated and partially functioning course on udemy.com. In previous modules, I managed to successfully receive content through routes like app.get('/vegetables',functio ...

The issue arises when attempting to update the input of a child component within a reactive form during the OnInit lifecycle

My dilemma arises in working with data stored in the ngrx entity store, as it gets displayed in chunks based on pagination. The issue lies with rxjs somehow remembering the paging history. For instance, when I fetch the first page of data from the server, ...

What is the best way to retrieve form values on the server in nextJs?

I'm facing an issue with passing form data to my API endpoint in nextJS. I have set up the form using Formik and Yup for validation. Oddly, when I check the console on the client side, I can see the user input values just fine, but on the server side, ...

When using jQuery, the search for the ID within an iframe may fail if the specified condition

I have a scenario where I need to dynamically generate an iframe and its corresponding id. Now, I need to check if the generated id already exists or not. This is what my code looks like: function createIframe(intxnId){ alert("The Id is : "+"$(&apo ...

Boost Google Pagespeed score by reducing 'Total Blocking Time' in NextJs

I've recently started using NextJS and I'm looking to improve my Google Pagespeed ranking. So far, I've made some good progress in optimizing different metrics. From the screenshot provided, it's clear that the only issue remaining i ...

Is there a method to directly download large files from the server without having to wait for the blob response?

I'm currently working on video file requests using axios. I have set the requests with responseType: blob to create a video player once the response is received with window.URL.createObjectUrl(). However, I also have a button that allows the user to d ...