简体   繁体   中英

Creating stopwatch using Javascript: Having trouble with click event

I'm currently working on this Mozilla Developer Network's project . The assignment is to create a stop watch using the date object and some plain old Javascript, and things are coming together slowly.

I've figured out the logic behind showing the elapse of time using the Date.now() method, and have been able to show a successful elapse of time. Only issue is, this only happens when the html element is clicked. I want the elapse of time to continue showing on the screen without having to keep clicking.

Does anyone know how I could do this?

Here's the link to the assignment: https://github.uconn.edu/pages/ssw19002/dmd-3475/Week-9/stop-watch/stop-watch.html

Here's the code so far:

function displayTime() {
  let date = new Date();
  let time = date.toLocaleTimeString();
  document.querySelector('.clock').textContent = time;
}


const createClock = setInterval(displayTime,1000);


//add click event to start button
let startBtn = document.getElementById("start-button");

startBtn.addEventListener('click', function(){
  document.querySelector('.clock').textContent = setInterval(function startTime(){startTime - Date.now()}, 1000);

  const createClock = setInterval(startTime,1000);
});

Here is one I made for command line use. Perhaps you can modify it for browser use:

function format(d) {
   let mil = String(d % 1000).padStart(3, '0');
   d = Math.trunc(d / 1000);
   let sec = String(d % 60).padStart(2, '0');
   d = Math.trunc(d / 60);
   return String(d) + ' m ' + sec + ' s ' + mil + ' ms';
}

function main() {
   console.clear();
   let s = format(Date.now() - n);
   console.log(s);
}

let n = Date.now();
setInterval(main, 10);

https://89z.github.io/autumn/return-duration-string/js

Just the first two definitions should be enough for the clock part. setInterval will start an interval that calls displayTime every second. Make a second function displayElapsedTime that is similar to displayTime , and inside the startBtn click handler, stop the displayTime interval (you'll need to hold onto the result of the setInterval call to be able to do this) and start the displayElapsedTime interval. As always, read the best / most official documentation you can find on how to do this.

The code you posted has a bug - the body of the function you named startTime contains a reference to a variable named startTime - which will then point to the function startTime . It seems you named the function itself startTime instead of naming a variable defined inside the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM