How to get current time from browser in JavaScript

Current Time From Browser

The current time is:



We can get the current time with built- in JavaScript object Date

To get the time we have to create the Date object first simply like this

let currentDateTime = new Date();

As we created the date object

we can console.log to get the result

console.log(currentDateTime);

We get the result like this.

Sun Jun 16 2024 10:26:41 GMT+0600 (Bangladesh Standard Time)

we can separate the date in hour minute and seconds

let currentDateTime = new Date();

// Extract hours, minutes, and seconds from the current date and time


let currentHours = currentDateTime.getHours();
let currentMinutes = currentDateTime.getMinutes();
let currentSeconds = currentDateTime.getSeconds();

example code

// Step 1: Create a Date object
let currentDateTime = new Date();

// Step 2: Display the current date and time
console.log(currentDateTime);

// Step 3: Get the current hour, minute, and second
let currentHours = currentDateTime.getHours();
let currentMinutes = currentDateTime.getMinutes();
let currentSeconds = currentDateTime.getSeconds();

// Step 4: Display the hour, minute, and second
console.log('Current Hours: ' + currentHours);
console.log('Current Minutes: ' + currentMinutes);
console.log('Current Seconds: ' + currentSeconds);

A complete example where time gets from browser and update every second



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-Time Current Time Display Example</title>
    <script>
        // Function to retrieve and display the current time
        function getCurrentTimeAndDisplay() {
            // Create a new Date object to get the current date and time
            let currentDateTime = new Date();

            // Extract hours, minutes, and seconds from the current date and time
            let currentHours = currentDateTime.getHours();
            let currentMinutes = currentDateTime.getMinutes();
            let currentSeconds = currentDateTime.getSeconds();

            // Format hours, minutes, and seconds to ensure they are always two digits
            currentHours = currentHours < 10 ? '0' + currentHours : currentHours;
            currentMinutes = currentMinutes < 10 ? '0' + currentMinutes : currentMinutes;
            currentSeconds = currentSeconds < 10 ? '0' + currentSeconds : currentSeconds;

            // Construct the time string in HH:MM:SS format
            let formattedTimeString = currentHours + ':' + currentMinutes + ':' + currentSeconds;

            // Display the formatted time string in an HTML element with id "currentTimeDisplay"
            document.getElementById('currentTimeDisplay').textContent = formattedTimeString;
        }

        // Update the displayed time every second (1000 milliseconds)
        setInterval(getCurrentTimeAndDisplay, 1000);
    </script>
</head>
<body>
    <h1>Real-Time Current Time Display</h1>
    <p>The current time is: <span id="currentTimeDisplay"></span></p>
</body>
</html>


    
    
    

You can Copy the example code and practice the code directly here

How to Make Analog Clock with HTML, CSS, and JavaScript

Simple Clock
12
3
6
9

The structure and the essentials

  • We need second , minute and hour hand,
  • second hand will circle through 360 degree every minute that means in every second it will move 6 degree
  • Minute hand moves 6 degree in every minute
  • And the hour hand moves 30 degree every hour

So we just add this logic in the clock that's it.

We get the time from browser


const now = new Date();

const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();




Then access the clock hand from JavaScript


const hourHand = document.getElementById('hour-hand');
const minuteHand = document.getElementById('minute-hand');
const secondHand = document.getElementById('second-hand');



Update the position based on the current time


const hourDeg = (hours % 12) * 30 + minutes / 2;
const minuteDeg = minutes * 6;
const secondDeg = seconds * 6;

hourHand.style.transform = `rotate(${hourDeg}deg)`;
minuteHand.style.transform = `rotate(${minuteDeg}deg)`;
secondHand.style.transform = `rotate(${secondDeg}deg)`;


Add everything in a function also set interval of 1 second to update the clock every second


function updateClock() {
  const now = new Date();
  
  const hours = now.getHours();
  const minutes = now.getMinutes();
  const seconds = now.getSeconds();

  // Analog clock
  const hourHand = document.getElementById('hour-hand');
  const minuteHand = document.getElementById('minute-hand');
  const secondHand = document.getElementById('second-hand');

  const hourDeg = (hours % 12) * 30 + minutes / 2;
  const minuteDeg = minutes * 6;
  const secondDeg = seconds * 6;

  hourHand.style.transform = `rotate(${hourDeg}deg)`;
  minuteHand.style.transform = `rotate(${minuteDeg}deg)`;
  secondHand.style.transform = `rotate(${secondDeg}deg)`;

  // Digital clock
  const digitalClock = document.getElementById('digital-clock');
  digitalClock.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

// Update the clock every second
setInterval(updateClock, 1000);

// Initial call to set the clock right away
updateClock();


The complete code


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Simple Clock</title>
  <style>
    body {
      background-color: rgb(139, 126, 126);
    }
    .clock-container {
      color:#fffbe4;
      background-color: rgb(105, 96, 96);
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      font-family: Arial, sans-serif;
    }

    #analog-clock {
      border: 10px solid transparent;
      border-image: linear-gradient(to right, #b59d72, #ffe79a) 1;
      box-shadow: inset -1px 0px 12px 9px rgba(0, 0, 0, 0.5); 
      width: 300px;
      height: 300px;
      position: relative;
    }

    .clock-hand {
      box-shadow: 0 0 10px #00000080; 
      position: absolute;
      background:  linear-gradient(to right, #b59d72, #ffe79a);
      transform-origin: 50% 100%;
      width: 4px;
      top: 50%;
      left: 50%;
    }

    #hour-hand {
      height: 50px;
      margin-top: -50px;
    }

    #minute-hand {
      height: 70px;
      margin-top: -70px;
    }

    #second-hand {
      height: 80px;
      background:  linear-gradient(to right, #b59d72, #ffe79a);
      margin-top: -80px;
    }

    .hour-number-left-right {
      margin-top:-8px;
      position: absolute;
      font-size: 16px;
      font-weight: bold;
    }

    .hour-number-top-bottom {
      margin-left: -6px;
      position: absolute;
      font-size: 16px;
      font-weight: bold;
    }



    .hour-number {
      position: absolute;
      font-size: 16px;
      font-weight: bold;
    }

    .minute-dot {
      position: absolute;
      background-color: #333;
      width: 4px;
      height: 4px;
      border-radius: 50%;
    }

    #digital-clock {
      display: flex;
      position:absolute;
      margin-top:400px;
      font-size: 48px;
    }
  </style>
</head>
<body>
  <div class="clock-container">
    <div id="analog-clock">
      <!-- Clock Hands -->
      <div id="hour-hand" class="clock-hand"></div>
      <div id="minute-hand" class="clock-hand"></div>
      <div id="second-hand" class="clock-hand"></div>
      
      <!-- Hour Numbers -->
      <div class="hour-number-top-bottom" style="top: 10px; left: 50%;">12</div>
      <div class="hour-number-left-right" style="top: 50%; left: 95%;">3</div>
      <div class="hour-number-top-bottom" style="bottom: 10px; left: 50%;">6</div>
      <div class="hour-number-left-right" style="top: 50%; left: 5%;">9</div>

      <!-- Minute Dots -->
      <div class="minute-dot" style="top: 15%; left: 50%;"></div>
      <div class="minute-dot" style="top: 50%; left: 85%;"></div>
      <div class="minute-dot" style="bottom: 15%; left: 50%;"></div>
      <div class="minute-dot" style="top: 50%; left: 15%;"></div>
    </div>
    <div id="digital-clock"></div>
  </div>
  <script>
    function updateClock() {
      const now = new Date();
      
      const hours = now.getHours();
      const minutes = now.getMinutes();
      const seconds = now.getSeconds();

      // Analog clock
      const hourHand = document.getElementById('hour-hand');
      const minuteHand = document.getElementById('minute-hand');
      const secondHand = document.getElementById('second-hand');

      const hourDeg = (hours % 12) * 30 + minutes / 2;
      const minuteDeg = minutes * 6;
      const secondDeg = seconds * 6;

      hourHand.style.transform = `rotate(${hourDeg}deg)`;
      minuteHand.style.transform = `rotate(${minuteDeg}deg)`;
      secondHand.style.transform = `rotate(${secondDeg}deg)`;

      // Digital clock
      const digitalClock = document.getElementById('digital-clock');
      digitalClock.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }

    // Update the clock every second
    setInterval(updateClock, 1000);

    // Initial call to set the clock right away
    updateClock();
  </script>
</body>
</html>


Get the code from github
https://github.com/01one/analog-html-clock

Maximize web Performance: Overcome JavaScript Threading Limitations with Web Workers

Why?

Web Workers: A solution for overcoming JavaScript’s single-threaded limitations.

Running JavaScript tasks in background threads, separate from the main browser thread which is responsible for rendering the UI and handling user interactions.

So Its possible to run heavy task in multiple process and at the same time keep the ui responsive.

How?

The structure

Our Worker script (for example our-web-worker.js) A separate Script Which is responsible for maintaining the background task

Since the wokerscript runs seperately from our main website script so we need to set a communication between web-worker script and our main browser script.

postMessage: It used for send message in both sides. We can send instruction: the variable and other data to the worker script. and the worker script can send the result with it

onmessage: When one script( main script or worker script) postMessage other script get that message with onmessage.

Example

our-web-worker.js





self.onmessage = function(event) {
    const n = event.data;
    const result = calculateFibonacci(n);

    self.postMessage(result);
};

function calculateFibonacci(n) {
    var fib = [0, 1];
    for (let i = 2; i <= n; i++) {
        fib[i] = fib[i - 1] + fib[i - 2];
    }
    //return fib[n];
}




Our web-worker.html



<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Web Worker Example</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.5.0/semantic.min.css">
</head>
<body>
  <div class="ui container">
    <h2 class="ui header">Fibonacci Sequence Calculator</h2>
    <div class="ui action input">
      <input type="number" id="numberInput" placeholder="Enter a number...">
      <button class="ui button" onclick="calculateWithWorkers()">Calculate with Workers</button>
      <button class="ui button" onclick="calculateWithoutWorker()">Calculate without Worker</button>
    </div>
    <div id="resultWorkers" class="ui message hidden"></div>
    <div id="resultWithoutWorker" class="ui message hidden"></div>
  </div>

  <script>
    function calculateWithWorkers() {
      const number = parseInt(document.getElementById('numberInput').value);
      const startTime = performance.now();

      const workers = [];
      const workerResults = [];

      const numWorkers = 4;

      const range = Math.floor(number / numWorkers);

      for (let i = 0; i < numWorkers; i++) {
        const worker = new Worker('our-web-worker.js');

        worker.onmessage = function(event) {
          workerResults.push(event.data);

          if (workerResults.length === numWorkers) {
            const result = workerResults.reduce((acc, val) => acc + val, 0);
            displayResult('resultWorkers', result, startTime);
            workers.forEach(worker => worker.terminate());
          }
        };

        const start = i * range + 1;
        const end = (i + 1) * range;
        worker.postMessage({ start, end, number });
        
        workers.push(worker);
      }
    }

    function calculateWithoutWorker() {
      const number = parseInt(document.getElementById('numberInput').value);
      const startTime = performance.now();
      const result = calculateFibonacci(number);
      displayResult('resultWithoutWorker',result, startTime);
    }

    function calculateFibonacci(n) {
      var fib = [0, 1];
      for (let i = 2; i <= n; i++) {
        fib[i] = fib[i - 1] + fib[i - 2];
      }
      //return fib[n];
    }

    function displayResult(elementId, result='', startTime) {
      const resultElement = document.getElementById(elementId);
      const elapsedTime = (performance.now() - startTime).toFixed(2) + ' milliseconds';
      resultElement.classList.remove('hidden');
      resultElement.textContent = `Result: (Time taken: ${elapsedTime})`;
    }
  </script>
</body>
</html>




we applied 4 worker. To test the code run in a server.

If you test this directly in the browser you may face the security issue. To overcome this

setup a simple server for testing.

If you are on linux you can use python built in server

make sure terminal is open from your code directory.

python3 -m http.server

Then go to http://localhost:8000 and click on the web-worker.html

Try larger number for example 5 million to check the result in the user input. As we are testing the worker with Fibonacci number