Creating a personalized JavaScript clock based on a specific time

I have implemented a script below, and my goal is to customize the time displayed by the script and have it update automatically without requiring manual adjustment each time. (I want to set the time once and have the script manage the display)

However, upon running the script, it shows: NaN:NaN:NaN AM

The code snippet I am using is:

<div id="js_clock"> display clock here </div>

 <script language="javascript">
    function js_clock(clock_time)
    {   
         var clock_hours = clock_time.getHours();  
         var clock_minutes = clock_time.getMinutes();  
         var clock_seconds = clock_time.getSeconds();  
         var clock_suffix = "AM";     
         if (clock_hours > 11){
         clock_suffix = "PM";
         clock_hours = clock_hours - 12;
         }
         if (clock_hours == 0){
         clock_hours = 12;
         }

         if (clock_hours < 10){
         clock_hours = "0" + clock_hours;
         }

         if (clock_minutes < 10){
         clock_minutes = "0" + clock_minutes;
         }

         if (clock_seconds < 10){
         clock_seconds = "0" + clock_seconds;
         }

         var clock_div = document.getElementById('js_clock');
         clock_div.innerHTML = clock_hours + ":" + clock_minutes + ":" + clock_seconds + " " + clock_suffix;
         setTimeout("js_clock()", 1000);
    }

     var serverTime = new Date("09:20:50");
     js_clock(serverTime);
 </script>

Answer №1

Encountering an issue with creating the date, the code new Date("09:20:50"); results in Invalid Date.

If you need to specify hours, minutes, and seconds, you can use:

new Date(year, month, day [, hour, minute, second, millisecond])

For more information, you can refer to this link.

Furthermore, it seems like you missed passing a date to the setTimeout function, try this instead:

setTimeout(function() {
    js_clock(new Date(/*pass hours, minutes, and seconds here*/))
}, 1000);

Answer №2

Did you forget to include an argument when calling js_clock()? Perhaps you should try this:

setTimeout(
    function() {
        //Call the function again updating seconds by 1
        js_clock(
            new Date(
                clock_time.getFullYear(), 
                clock_time.getMonth(), 
                clock_time.getDate(), 
                clock_time.getHours(), 
                clock_time.getMinutes(), 
                clock_time.getSeconds() + 1
             )
        );
    }, 
    1000
);

UPDATE: I just realized this can actually be achieved with a single function call:

setTimeout(
    function() {
        js_clock(new Date(+clock_time + 1000));
    },
    1000
);

The +clock_time statement converts the Date object to milliseconds from the UNIX Epoch, so updating the time is as simple as adding 1000 milliseconds. Thanks goes to user RobG ;-)

Answer №3

Your code has some critical issues that need to be addressed:

The function setTimeout does not execute at the exact interval specified; instead, it runs as soon as possible after the set time, causing the clock to gradually drift out of sync.

Parsing a string into Date and assuming correct interpretation can lead to problems. In ECMA-262 ed 3, it was entirely dependent on implementation, and in ES5, the string must adhere to a custom ISO8601 long format (which may not be supported by all browsers).

Furthermore, if the client is busy, the function may experience delays of several seconds. Therefore, the clock should initially synchronize with the client's clock and then adjust for any time discrepancies.

The following optimized function resolves these issues.

<script type="text/javascript">
var customClock = (function() {

  var timeDifference;
  var timer;

  function addZero(n) {
    return (n < 10 ? '0' : '') + n;
  }

  function formatTime(date) {
    return addZero(date.getHours()) + ':' +
           addZero(date.getMinutes()) + ':' +
           addZero(date.getSeconds());
  }

  return function (startTime) {

    var currentTime = new Date();
    var targetTime;

    // Set lag to just after next full second
    var lag = 1015 - currentTime.getMilliseconds();

    // Calculate time difference on first run
    if (startTime) {
      startTime = startTime.split(':');
      targetTime = new Date(currentTime);
      targetTime.setHours(+startTime[0], +startTime[1], +startTime[2], 0);
      timeDifference = currentTime - targetTime;
    }

    currentTime = new Date(currentTime - timeDifference);

    document.getElementById('clock').innerHTML = formatTime(currentTime); 
    timer = setTimeout(customClock, lag);
  }
}());

window.onload = function() {
  customClock('09:20:50');
}

</script>

<div id="clock"></div>

Answer №4

Whoops! It looks like there's still a timing issue here. Although the error has been resolved, the displayed time is not accurate.

window.js_clock = function js_clock(clock_time) {
    var clock_hours = clock_time.getHours();
    var clock_minutes = clock_time.getMinutes();
    var clock_seconds = clock_time.getSeconds();
    var clock_suffix = "AM";
    if (clock_hours > 11) {
        clock_suffix = "PM";
        clock_hours = clock_hours - 12;
    }
    if (clock_hours === 0) {
        clock_hours = 12;
    }

    if (clock_hours < 10) {
        clock_hours = "0" + clock_hours;
    }

    if (clock_minutes < 10) {
        clock_minutes = "0" + clock_minutes;
    }

    if (clock_seconds < 10) {
        clock_seconds = "0" + clock_seconds;
    }

    var clock_div = document.getElementById('js_clock');
    clock_div.innerHTML = clock_hours + ":" + clock_minutes + ":" + clock_seconds + " " + clock_suffix;
    setTimeout("js_clock(new Date())", 1000);
}

var serverTime = new Date("09:20:50");
window.js_clock(serverTime);​

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

How to manually close the modal in Next.js using bootstrap 5

Incorporating Bootstrap 5.2 modals into my Next.js application has been smooth sailing so far. However, I've encountered an issue with closing the modal window after a successful backend request. To trigger the modal, I use the data-bs-toggle="modal" ...

What is causing the array elements to be iterated through multiple times?

My goal is to display all the titles from an array called 'title element' containing 10 values. However, I am encountering a problem: The for loop outputs all 10 values repeatedly 10 times. The titles are: Title 1, Title 2, Title 3, Title 4, T ...

AngularJS: handling multiple asynchronous requests

When I make multiple ajax calls in my code, I noticed that the API is only reached after all the ajax calls have been executed. Below you can see the JavaScript code: function test = function(){ var entity = {}; entity.Number = 1; ...

Tips for personalizing the NavigatorIOS's right side

Looking to create a navigation bar similar to Whatsapp's? I want to include a profile picture and call button on the right side of the bar. Any tips on how to achieve this look? Which properties should be used for this customization? Would it be bet ...

Having difficulty sending a message from an AngularJS application to an Angular 10 application through an iframe

I have two applications running locally - one is an AngularJS application and the other is an Angular 10 application. I am trying to access a page from the Angular 10 application using an iframe and send a message to it from the AngularJS application. How ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

How can I match all routes in Express except for '/'?

I've been working on implementing an authentication system for my app that involves checking cookies. My approach was to use router.all('*') to handle every request, verify the cookie, and then proceed to the actual handler. However, I encou ...

When utilizing the data-target attribute, the Bootstrap dropdown becomes toggled

My Bootstrap dropdown is giving me trouble when I use it with data target. Removing data-target from the button makes it work, but then my website's dropdown only opens on the second click. So I tried using data-target to fix it, but now it won' ...

Save array data to a file in Node.js once it finishes looping

I've been struggling to find a solution to my issue despite looking at examples from other questions. I have created a basic web scraper in nodejs that stores data in an array and now I need help writing this data to a file. I'm having difficulty ...

To link circles vertically with a line and fill them with color when clicked, follow these steps:

I am looking to create a design similar to the image below using unordered list items. When a user clicks on a list item, I want the circle to fill with color. I have structured it by creating a div with nested list items and span elements. If a user click ...

JavaScript counter to monitor the number of requests made to the Open Weather Map API

Currently, I am utilizing the Open Weather Map's free API which allows me to make 1000 API calls per day through their One Call API. However, there is no built-in feature for tracking these calls in the Open Weather Map platform. To address this issue ...

N8N: Deleting JSON Key from Output

Is it possible to remove the json key in my output file? I am unsure of the best approach to achieve this. I would like to return an array of data with all values, not just one value. If you want more information, here is a link to my N8N post: Manipulate ...

Searching Firebase by using comparison operators on various fields

const FindFiis = async () => { const data: any[] = []; // Firebase query with inequalities on different fields to retrieve docs. // Objective: Select documents where dividendYield is between 8 and 20 and pvp is less than or equal to 1. ...

Exploring the concept of event delegation: Understanding the difference between Event.target and

In the MDN Event.target reference, there is an example provided regarding event delegation: Example of Event Delegation // Assuming there is a 'list' variable containing an instance of an // HTML ul element. function hide(e) { // Unless l ...

Guide to utilizing Materialize with Angular 2

For the past 2 days, I've been struggling with an issue. I'm fairly new to Angular 2 and I'm attempting to use Materialize with Angular 2. I managed to resolve a couple of errors that were asking me to update the TypeScript version, which I ...

How to efficiently await multiple promises in Javascript

My Objective: Collect artist IDs Find them in the database Create new ones if needed Create an event record in the database and obtain its ID Ensure all artist IDs and event ID are gathered before proceeding Loop through combin ...

What is the best way to accomplish this task using JavaScript fetch?

I stumbled upon this solution. Essentially, it's a call to Mailchimp requesting a confirmation email be sent to users after submitting their email. The script functions flawlessly with jquery. However, I have a distaste for jquery and find it bother ...

Setting the z-index for data points in a scatter plot on HighCharts

Utilizing HighCharts to display a large number of points on a plot. Each point has an opacity setting and changes to red when selected. However, some points are difficult to distinguish due to overlapping. I would like the selected point to be easily visi ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

An old-school Ajax request abruptly interrupted halfway through

function submitLogin(){ var username = document.getElementById('username').value; var password = document.getElementById('password').value; var testlabel = document.getElementById('testlabel').value; ...