0

i have no clue how to preform javascript loops all i want to do is simply update the code below every second so it provides the correct time after the user presses the button

<button type="button"
onclick="document.getElementById('time').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

what are some ways that could be used to make it run every second but not require the user to press the button more than once

  • 1
    change the id of the `

    ` to `time`

    – Taki Apr 12 '21 at 15:31
  • Try using [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) – Rojo Apr 12 '21 at 15:32
  • 1
    If you want the time to be updated when the user clicks the button, there's no need to do anything every second. Just respond to the button click (as you are). As @Taki pointed out, the main problem with the above is that it's using the wrong ID value (`time` instead of `demo`). (A second problem is that `onxyz`-attriute-style event handlers aren't best practice; look into using `addEventListener`.) – T.J. Crowder Apr 12 '21 at 15:34
  • Try `onclick="setInterval(function(){document.getElementById('time').innerHTML = Date()}, 1000);"` – Spectric Apr 12 '21 at 15:36

0 Answers0