0

I am having trouble to find the way to stop this clock in JavaScript

I was expecting the clock to stop working after pressing stop but it keeps going

<!DOCTYPE html>
<html>
<head>  
 
<h1> Welcome to the clock. Press the stop button to stop the clock <h1>
<h2> This clock goes for 24 hours at 100 miloseconds</h2>
<div id="clock"></div>
<script>
const clockElement = document.querySelector('#clock');
 
const stopButton = document.querySelector('#stopbutton');
 
let clockInterval = setInterval(() => {
 
let currentTime = new Date();
 
clockElement.innerHTML = currentTime.toLocaleTimeString();
}, 100);
 
stopButton.addEventListener('click', () => {
  clearInterval(clockInterval);
});
</script>
<button id="stopbutton">Stop</button>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

2 Answers2

1

The code in the script tag is running before the browser "rendered" the button. You should put the button element above the script tag or tell the code to wait until the entire website has loaded with window.onload

Hidayt Rahman
  • 2,490
  • 26
  • 32
Taureon
  • 75
  • 1
  • 9
0

Move this to the end of code should work, it will explain what happened

<script>
const stopButton = document.querySelector('#stopbutton');
stopButton.addEventListener('click', () => {
  clearInterval(clockInterval);
});
</script>
Nate Cheng
  • 414
  • 6
  • 11