How can I write a code that updates a function every single second?

I had a simple idea to create a clock that only shows the time, not the date. The issue I encountered with the code provided is that it displays the time when the .html file is initially opened.

<body onload="showTime()">
<p id="time"></p>
<script>
var seconds;
var minutes;
var hours;
var currentTime;

function showTime() {
    seconds = getSeconds();
    minutes = getMinutes();
    hours = getHours();
    document.getElementById("demo").innerHTML =
    hours +":"+ minutes +":"+ seconds; 
}

Is there any way for me to make it update automatically every second? Appreciate any help!

Answer №1

If you don't want to run the code within a body tag, you will need setInterval and a proper date object.

<!DOCTYPE html>
<html>
  <head>
    <title>Clock</title>
    <script>
      window.onload=function() {
        setInterval(showTime,500); // execute every 500ms
      }
      function pad(num) {
        return ("0"+num).slice(-2); // add leading 0 if needed
      } 
      function showTime() {
        var d    = new Date(), // current time
         seconds = d.getSeconds();
         minutes = d.getMinutes();
         hours   = d.getHours();
         document.getElementById("demo").innerHTML = pad(hours) +":"+ pad(minutes) +":"+ pad(seconds); 
      } 
      </script>    
    </head>
    <body>
      <p id="demo"></p>
   </body>
</html>

Answer №2

To achieve running the function every second, consider utilizing the setInterval() method. For further information on this topic, check out Run JavaScript function at regular time interval - while not guaranteed to be the optimal solution, it could potentially be effective...

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

What would be the best way to handle a file path provided to a module in Node.js?

As I embark on my journey to develop my first Node.js module, one dilemma that has surfaced is how to handle user-input paths efficiently. What approach is highly recommended for accepting file paths from users as input? Furthermore, once the paths are rec ...

Python: passing a function as a parameter

Exploring the concept of passing functions as arguments to other functions has sparked a question in my mind: Is it possible to set a fixed value for some of the parameters when passing a function as an argument, in addition to their default value? For exa ...

Encountering an issue with getDerivedStateFromProps in React where an error states: Unable to retrieve property 'setState' of null

Just found out that componentWillReceiveProps is deprecated and now we should be using the getDerivedStateFromProps lifecycle method. You can find more information about it at this link. This is how I'm implementing it: class Main extends Component ...

Passing React components between components using dot notation

How can I pass a boolean Parent prop into a child component using dot notation with a functional component? The Component structure is: <Dropdown className="float-right"> <Dropdown.Title>Open menu</Dropdown.Title> <Dropd ...

Switching a cookie from JavaScript to AngularJS: A step-by-step guide

Getting a cookie in AngularJS can be done in a more standardized way. Instead of the traditional JavaScript approach, you can implement it using AngularJS code as shown below: angular.module('myApp', []) .factory('CookieService', func ...

Draggable resizing of the Accordion component in React.js using Material-UI

In the visual representation, there are two Accordions—one positioned on the left (30%) and the other on the right (70%). Upon clicking the button, the right accordion disappears, while the one on the left expands to cover the full width (100%). A featu ...

How can I launch five separate instances of Chrome on a Selenium grid, each with a different URL?

I have a list of URLs saved in a JSON file, structured like this: { "urls": [ "http://www.google.com/", "http://www.stackoverflow.com" ] } Currently, these URLs are being opened sequentially by the Selenium WebDriver JavaScript manager on a ...

Why is it not possible for me to require SceneExporter in node.js?

Hey there, I have a question. I am having trouble using SceneExporter in node.js, and I will provide some examples to explain: THREE = require 'three' - I have included the module that I installed in node.js Export = require './SceneExporte ...

Executing a function from another reducer using React and redux

My application consists of two main components: the Market and the Status. The Status component manages the user's money, while the Market component contains buttons for purchasing items. My goal is to decrement the user's money when a button in ...

Integration of Formspree (HTML) and JavaScript causes conflicts with Toastr library, resulting in malfunctioning of both functionalities simultaneously

I have integrated Formspree (https://formspree.io/) to redirect form submissions to my email on a static website. Additionally, I am utilizing Toastr (http://codeseven.github.io/toastr/) to display a notification upon clicking the 'Submit' button ...

What is the method for returning a string array?

My query is about how to return a string[]. Currently, TypeScript is throwing an error because each element of the array has a type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] ). How can I accept the 'property' arg ...

How can you ensure that the Data Point Values are always displayed when using arrayToDataTable in the Google Charts API?

Just wanted to clarify that even though there is a similar question titled: Google Charts API: Always show the Data Point Values in Graph ...on this website, I am facing difficulties implementing its solution because my chart is using arrayToDataTable. ...

Execute the onclick function of an element using JQuery in an ASP.NET application

My ASP.NET server control is customized to inherit from CheckBoxList, rendering the controls with a UL and LIs and set to AutoPostBack. Here is the markup I am using: <div id="foo"> <ul> <li> <input id="..." ...

What is the best way to retrieve both the start and end date values from a React date range picker component

I have integrated a date range picker npm package called react-date-range into my code. On my screen, there is an "Apply Dates" button. When this button is clicked, I want to retrieve the selected date range value. How can I achieve this onclick event? ...

Having difficulty with loading images lazily in a jQuery Mobile app with LazyLoadXT feature

Struggling to incorporate lazy loading in my jQM app with Lazy Load XT v1.0.6. Oddly, images only appear when switching browser tabs, not while scrolling down. This happens on Firefox and Chrome. <img src="/img/default-img.jpg" data-src="/img/product/ ...

What steps should I take to ensure that the child menus of the v-navigation-drawer component are activated during the initial project launch?

I have created a v-navigation-drawer component with Vue 3 and Vuetify 3. The v-navigation-drawer functions properly, but I want the child menus to be visible by default without requiring the user's click when the project first launches. I am using v- ...

Choosing an option in react-select causes the page to unexpectedly shift

Encountering a problem with a mobile modal developed using react-select. The selectors are within a div with fixed height and overflow-y: scroll. Upon selecting an option for the 'Choose observer' select, the entire modal briefly jumps down in th ...

Selenium IDE's float calculation in javascript results in a value of 1 instead of the expected 1.99

I am trying to perform a JavaScript evaluation in Selenium IDE that involves multiplying 3 decimal values. javascript{parseFloat(storedVars['val1'])*parseFloat(storedVars['val2'])*parseFloat(storedVars['val3'])} However, whe ...

Remove the click event once the sorting process has been completed

I am currently working on a project that involves creating a list of sortable images using jquery sortable. Users can easily drag and drop the images for sorting purposes. Additionally, each image's parent anchor has a click event attached to open it ...

Steer clear of using the character sequence "&#8220;" in both PHP and

I am struggling with the encoding (I think). A script I wrote fetches a PHP file through AJAX that generates a JSON file. The JSON file appears as follows in Firebug: ["&#8220;This is a word&#8221; This not"] I am trying to find a way to remove & ...