skip to Main Content

I have this javascript stopwatch that is working. The function is when user click start button to start and pause button to pause the stopwatch. The variable stopwatch is saved in localStorage and when user refresh the website and click start again the stopwatch continue from the last stopwatch time + 1; The first timer is working, but I will have an array of the same containers, fetching from a Database containing stopwatch time. The problem is with my loop. How can I add the timer for each individual timer container and continue from the time it was last saved + 1 and continue from there. I am providing an example maybe someone can help me.

HTML

<div class="c-add-task-main-container">
    <h2 class="c-add-task-title">Time Tracker</h2>
    <button class="start">Start</button>
    <button class="pause">Pause</button>
    <button class="clear">Clear</button>
    <div class="output">00:34:21</div>
</div>

<div class="c-add-task-main-container">
    <h2 class="c-add-task-title">Time Tracker</h2>
    <button class="start">Start</button>
    <button class="pause">Pause</button>
    <button class="clear">Clear</button>
    <div class="output">21:56:22</div>
</div>

<div class="c-add-task-main-container">
    <h2 class="c-add-task-title">Time Tracker</h2>
    <button class="start">Start</button>
    <button class="pause">Pause</button>
    <button class="clear">Clear</button>
    <div class="output">32:47:35</div>
</div>

<div class="c-add-task-main-container">
    <h2 class="c-add-task-title">Time Tracker</h2>
    <button class="start">Start</button>
    <button class="pause">Pause</button>
    <button class="clear">Clear</button>
    <div class="output">11:29:03</div>
</div>

<div class="c-add-task-main-container">
    <h2 class="c-add-task-title">Time Tracker</h2>
    <button class="start">Start</button>
    <button class="pause">Pause</button>
    <button class="clear">Clear</button>
    <div class="output">04:01:14</div>
</div>

JS

    let showTime = document.querySelector(".output");
    let startTimeButton = document.querySelector(".start")
    let pauseTimeButton = document.querySelector(".pause")

    let seconds = 0;
    let interval = null;
    if (localStorage.getItem("stopwatchSeconds") != null) {
        seconds = parseInt(localStorage.getItem("stopwatchSeconds"));
    }

    const timer = () => {
        seconds++;

        localStorage.setItem("stopwatchSeconds", seconds);


        // Get hours
        let hours = Math.floor(seconds / 3600);
        // Get minutes
        let minutes = Math.floor((seconds - hours * 3600) / 60);
        // Get seconds
        let secs = Math.floor(seconds % 60);

        if (hours < 10) {
            hours = `0${hours}`;
        }
        if (minutes < 10) {
            minutes = `0${minutes}`;
        }
        if (secs < 10) {
            secs = `0${secs}`;
        }

        showTime.innerHTML = `${hours}:${minutes}:${secs}`;

    };

    startTimeButton.addEventListener("click", () => {
        pauseTimeButton.style.display = "block";
        startTimeButton.style.display = "none";
        console.log("START TIME CLICKED");

        if (interval) {
            return;
        }

        interval = setInterval(timer, 1000);
    });

    // Pause function
    pauseTimeButton.addEventListener("click", () => {
        pauseTimeButton.style.display = "none";
        startTimeButton.style.display = "block";
        console.log("PAUSE TIME CLICKED");
        clearInterval(interval);
        interval = null;

    });

2

Answers


  1. You can try this snippet

    Html

    <div class="c-add-task-main-container" data-watch_no="01">
      <h2 class="c-add-task-title">Time Tracker 01</h2>
      <button class="start">Start</button>
      <button class="pause">Pause</button>
      <button class="clear">Clear</button>
      <div class="output"></div>
    </div>
    
    <div class="c-add-task-main-container" data-watch_no="02">
      <h2 class="c-add-task-title">Time Tracker 02</h2>
      <button class="start">Start</button>
      <button class="pause">Pause</button>
      <button class="clear">Clear</button>
      <div class="output"></div>
    </div>
    

    Vanilla JS

    let stop_watch_containers = document.querySelectorAll(".c-add-task-main-container");
    
    stop_watch_containers.forEach((container) => {
    
        let start_button = container.querySelector(".start");
        let pause_button = container.querySelector(".pause");
        let clear_button = container.querySelector(".clear");
        let output = container.querySelector(".output");
        let localStorageKey = "watch" + container.dataset.watch_no;
        let seconds = localStorage.getItem(localStorageKey);
    
        if (isNaN(seconds)) {
            seconds = 0;
        }
    
        // set old time on page load
        output.innerHTML = timer();
    
        let interval;
    
        // start watch
        start_button.addEventListener("click", function () {
            clearInterval(interval);
            interval = setInterval(function () {
            output.innerHTML = timer();
            seconds++;
            }, 1000);
        });
    
        // pause watch
        pause_button.addEventListener("click", function () {
            clearInterval(interval);
            localStorage.setItem(localStorageKey, seconds);
        });
    
        // clear watch
        clear_button.addEventListener("click", function () {
            clearInterval(interval);
            seconds = 0;
            output.innerHTML = timer();
            localStorage.setItem(localStorageKey, 0);
        });
    
        function timer() {
            let hours = Math.floor(seconds / 3600);
            // Get minutes
            let minutes = Math.floor((seconds - hours * 3600) / 60);
            // Get seconds
            let secs = Math.floor(seconds % 60);
    
            if (hours < 10) {
            hours = `0${hours}`;
            }
            if (minutes < 10) {
            minutes = `0${minutes}`;
            }
            if (secs < 10) {
            secs = `0${secs}`;
            }
            return `${hours}:${minutes}:${secs}`;
        }
    });
    
    Login or Signup to reply.
  2. Save the interval and timer in array let seconds = [] and I simplified your code, Start and Pause button are merged, if (time < 10) change with .padStart()

    run on jsFiddle

    let startTimeButtons = document.querySelectorAll(".start")
    
    let seconds = [0, 0];
    let interval = [];
    if (localStorage.getItem("stopwatchSeconds") != null) {
      seconds = JSON.parse(localStorage.getItem("stopwatchSeconds"));
      seconds = seconds.map(n => parseInt(n))
    }
    
    const timer = (el, i) => {
      seconds[i]++;
      localStorage.setItem("stopwatchSeconds", JSON.stringify(seconds));
      // Get hours
      let hours = Math.floor(seconds[i] / 3600).toString().padStart(2, 0);
      // Get minutes
      let minutes = Math.floor((seconds[i] - hours * 3600) / 60).toString().padStart(2, 0);
      // Get seconds
      let secs = Math.floor(seconds[i] % 60).toString().padStart(2, 0);
    
      el.parentElement.querySelector('.output').innerHTML = `${hours}:${minutes}:${secs}`;
    
    };
    
    startTimeButtons.forEach((btn, index) => {
      timer(btn, index); // update time on page load
      btn.addEventListener("click", () => {
        if (btn.textContent == 'Start') {
          btn.textContent = 'Pause';
          interval[index] = setInterval(timer, 1000, btn, index);
        } else {
          btn.textContent = 'Start';
          clearInterval(interval[index]);
        }
      });
    })
    <div class="c-add-task-main-container">
        <h2 class="c-add-task-title">Time Tracker</h2>
        <button class="start">Start</button>
        <button class="clear">Clear</button>
        <div class="output">00:00:00</div>
    </div>
    
    <div class="c-add-task-main-container">
        <h2 class="c-add-task-title">Time Tracker</h2>
        <button class="start">Start</button>
        <button class="clear">Clear</button>
        <div class="output">00:00:00</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search