A stopwatch written in JavaScript ⏱️

Поділитися
Вставка
  • Опубліковано 25 лис 2024

КОМЕНТАРІ • 70

  • @BroCodez
    @BroCodez  2 роки тому +33

    const timeDisplay = document.querySelector("#timeDisplay");
    const startBtn = document.querySelector("#startBtn");
    const pauseBtn = document.querySelector("#pauseBtn");
    const resetBtn = document.querySelector("#resetBtn");
    let startTime = 0;
    let elapsedTime = 0;
    let currentTime = 0;
    let paused = true;
    let intervalId;
    let hrs = 0;
    let mins = 0;
    let secs = 0;
    startBtn.addEventListener("click", () => {
    if(paused){
    paused = false;
    startTime = Date.now() - elapsedTime;
    intervalId = setInterval(updateTime, 1000);
    }
    });
    pauseBtn.addEventListener("click", () => {
    if(!paused){
    paused = true;
    elapsedTime = Date.now() - startTime;
    clearInterval(intervalId);
    }
    });
    resetBtn.addEventListener("click", () => {
    paused = true;
    clearInterval(intervalId);
    startTime = 0;
    elapsedTime = 0;
    currentTime = 0;
    hrs = 0;
    mins = 0;
    secs = 0;
    timeDisplay.textContent = "00:00:00";
    });
    function updateTime(){
    elapsedTime = Date.now() - startTime;
    secs = Math.floor((elapsedTime / 1000) % 60);
    mins = Math.floor((elapsedTime / (1000 * 60)) % 60);
    hrs = Math.floor((elapsedTime / (1000 * 60 * 60)) % 60);
    secs = pad(secs);
    mins = pad(mins);
    hrs = pad(hrs);
    timeDisplay.textContent = `${hrs}:${mins}:${secs}`;
    function pad(unit){
    return (("0") + unit).length > 2 ? unit : "0" + unit;
    }
    }



    Document


    00:00:00
    Start
    Pause
    Reset


    .timerBtn{
    width: 80px;
    height: 30px;
    border: 3px solid;
    border-radius: 12px;
    background-color: #333333;
    color: white;
    cursor: pointer;
    font-family: consolas, monospace;
    }
    #timeDisplay{
    font-size: 75px;
    color: #40c437;
    font-family: consolas, monospace;
    }
    #timeContainer{
    text-align: center;
    border: 3px solid;
    border-radius: 25px;
    background-color: #222222;
    }

    • @bo4695
      @bo4695 2 роки тому +1

      Thanks for the tutorial mate! A question, is the %60 necessary? may I know what is the function of it in the statement? thank you!

    • @marxLz
      @marxLz 2 роки тому

      @@bo4695 the %60 means that each of the units (seconds, minutes, hours) won't exceed by 60 counts which will stop at 59 counts then back to 0, then the 60th count with therefore be pass on to the next unit which is on its left side.
      I think he has even better explanation on java programming playlist. I started watching his videos in the 100 java playlist. You can see the stopwatch he also programmed there.

    • @Blinyxdd
      @Blinyxdd 2 роки тому +1

      Gotta say I noticed we added currentTime but never used it.

    • @Axel.Blazer
      @Axel.Blazer 2 місяці тому

      bro's github is yt comments

  • @rastgo4432
    @rastgo4432 2 роки тому +5

    So glad that you started uploading videos again, very amazing tutorials thanx for all your efforts, hope we see more amazing tutorials from this channel

  • @jermiahcoleman8690
    @jermiahcoleman8690 2 роки тому +5

    You read my mind let's go I always wanted to practice making projects to enhance my skills because your teaching strategy is just amazing

  • @ViolettaNjombwa
    @ViolettaNjombwa 8 місяців тому

    This has made things for me more easier ❤

  • @shreehari2589
    @shreehari2589 2 роки тому +2

    Really loving these mini projects, thanks bro

  • @tn11_deadpool87
    @tn11_deadpool87 2 роки тому +4

    while(true)
    {
    print=your are really great;
    }

  • @малосольные-окурки
    @малосольные-окурки 6 місяців тому

    it's time to learn something new. love your content!

  • @icy_invader
    @icy_invader Рік тому +1

    you very best bro 😁 thankyou for this tutorial 😊

  • @akshayav1035
    @akshayav1035 Рік тому

    just so know, BRO i am a fan! good one.

  • @markmcla
    @markmcla 2 роки тому

    Thanks for sharing this! Your example is very helpful.

  • @anonimanonim1223
    @anonimanonim1223 2 роки тому +1

    Very good videos

  • @sainy1048
    @sainy1048 2 роки тому

    Now I understand 😃 which line should be first and which line should be next

  • @khalidelgazzar
    @khalidelgazzar 6 місяців тому

    Great tutorial thank you

  • @LFF5644
    @LFF5644 Рік тому +1

    nice video!!
    use console.log(String(secs).padStart(2,"0"))

  • @codebitcookie8053
    @codebitcookie8053 2 роки тому +1

    Thanks, I feel like I have found a gold mine with your channel. Thanks for such informative content. I know you have a small view count but the people who do watch your videos love them, so, keep up the good work!

  • @yoshimochii
    @yoshimochii 2 роки тому +13

    very disheartening seeing your view count slowly plummet man, even though your content is sooooooooo goood :(((( I hope your videos gets algorithm'd by UA-cam

    • @bossbearfan3056
      @bossbearfan3056 2 роки тому

      i think it’s cause he posts a lot of short videos but his longer tutorials still get lots of views

    • @kartikchauhan2778
      @kartikchauhan2778 2 роки тому

      Its an unlisted video

  • @NOTHING-en2ue
    @NOTHING-en2ue Рік тому

    you're amazing man ❤

  • @speedskeleton250
    @speedskeleton250 2 роки тому +1

    Cool timer! But what did i understand from the codes?
    Html: a little bit
    CSS: more than html
    JS:...
    Nothing
    Idk i havent leaent those languages but i tried html in notebook...

    • @julfinch
      @julfinch 2 роки тому +1

      This project is the 86th video in his “Javascript tutorial for beginners” playlist. It is expected that when you try this project out, you already know the basic of JS by watching the previous videos. I just watched all of them and I’m already in this part when I read your comment, believe me, it’s easier to understand now all of his explanations and codes. Of the many Javascript Tutorials out there, BroCode’s teaching style is what suits me, direct to the point, concise, clear and short. Instead of the 8-hour long version of his tutorial which is very intimidating cause it’s long and boring, I watched the playlist version where each topics are separated in each video, in that way, it won’t feel tedious and you’ll get satisfaction for the progress you’ve made for every video you will finish: ua-cam.com/play/PLZPZq0r_RZOMRMjHB_IEBjOW_ufr00yG1.html

  • @robertnexus77
    @robertnexus77 2 роки тому

    you are great

  • @bomapdich
    @bomapdich Рік тому

    Im confused of the use of the variable "pause". Why do we need this boolean variable

  • @marxLz
    @marxLz 2 роки тому

    Random comment for the youtube algorithm. 👍👍👍🙏🙏🙏

  • @vasanthkumar.r2700
    @vasanthkumar.r2700 Рік тому +1

    Hi sir ..
    Am run this my vs code.
    It does not run why?

  • @kaolin-x4790
    @kaolin-x4790 2 роки тому

    My bro I need more javaScript projects.

  • @lucabinder9829
    @lucabinder9829 2 роки тому

    Nice one!

  • @DavidR212
    @DavidR212 Рік тому

    thank you so much

  • @pav4540
    @pav4540 Рік тому

    Thanks bro

  • @sagidkhair98
    @sagidkhair98 Рік тому

    Bro ... can u make an ecom website tutorial

  • @vicentenitti4141
    @vicentenitti4141 9 місяців тому

    "secs = 0"
    Me too pal.

  • @lyon8539
    @lyon8539 Рік тому

    Help,
    My JS don’t work. On the html file

  • @PrankIncluded
    @PrankIncluded 2 роки тому

    Osm video ❤️

  • @mohammedmasthanvali1039
    @mohammedmasthanvali1039 2 роки тому +1

    can you make that pause button to resume when it is paused? and when we click resume it should start from where it stopped....

    • @gamemekaniktr7562
      @gamemekaniktr7562 2 роки тому +2

      bro just change the pauseBtn event listener to this
      pauseBtn.addEventListener("click", () => {
      if (paused) {
      paused = false;
      startTime = Date.now() - elapsedTime;
      intervalId = setInterval(updateTime, 1000);
      }

      else{
      paused = true;
      elapsedTime = Date.now() - startTime;
      clearInterval(intervalId);
      }
      });
      but still start button can do the same

    • @mohammedmasthanvali1039
      @mohammedmasthanvali1039 2 роки тому

      @@gamemekaniktr7562 thank you brother I'll try this

    • @markmcla
      @markmcla 2 роки тому

      It might be too late to help, but this is what I did: startBtn.addEventListener("click", () => {
      let case1State = 0;
      let case2State = 0;
      if (isStopped == 1){
      //button is clicked. Present state is: Timer is stopped. (need to start or resume timing. change button text to 'stop')
      case1State = 1;
      }

      if ((isStopped == 0) && (isReset === 0)){
      //button is clicked. Present state is: Timer is running. Timer is not reset. (need to stop timing. change button text to 'resume')
      case2State = 1;
      }
      if (case1State === 1){
      isStopped = 0;
      isReset = 0;
      startBtn.innerText = "Stop";
      startBtn.style.backgroundColor = "red";
      startTime = Date.now() - elapsedTime;
      intervalId = setInterval(updateTime, 10);
      }
      if (case2State === 1){
      isStopped = 1;
      startBtn.innerText = "Resume";
      startBtn.style.backgroundColor = "#0000FF";
      clearInterval(intervalId);
      }
      }); (And in the other lines of code, I changed all of the boolean variables to 0's and 1's)

  • @AbduqodirRixsiboyev-i3f
    @AbduqodirRixsiboyev-i3f Рік тому

    thank you bro

  • @bLitzKinG20
    @bLitzKinG20 2 роки тому

    Thanks man!

  • @user-fz1cj8rh6k
    @user-fz1cj8rh6k 2 роки тому +1

    What is the need of using "elapsedTime = Date.now() - startTime; " inside "pauseBtn.addEventListener()" ?

  • @fr1endsies
    @fr1endsies 2 роки тому

    Good video Bro! can we have some more of these projects if you have the time to do so please?

  • @foxie777
    @foxie777 2 роки тому

    Thank you bro, great video. How can we add milliseconds to this timer? I'm trying but can't really make it work fast, it counts same as seconds :S

  • @rudrarajkar1116
    @rudrarajkar1116 2 роки тому

    is this what consistency is?

  • @AyomideYusuf-jv2mm
    @AyomideYusuf-jv2mm 2 місяці тому +1

    Secs 🤔🤔

  • @nayabshaik7702
    @nayabshaik7702 2 роки тому

    Bro please do some small projects in python

  • @augischadiegils.5109
    @augischadiegils.5109 2 роки тому

    ❤️❤️❤️❤️

  • @limu3749
    @limu3749 Рік тому

    What is the use of let currentTime = 0?

    • @time0psy
      @time0psy 9 місяців тому

      Here, no use. Maybe meant for later.

  • @clrkkdd12
    @clrkkdd12 2 роки тому +1

    👊🏽

  • @AmericanDragon134
    @AmericanDragon134 2 роки тому +2

    Bro code what is your real name?

    • @Pavann
      @Pavann 2 роки тому

      Chris is our bro

  • @angelcross6050
    @angelcross6050 2 роки тому

    Yo, I've been watching this same video for 2 days now and cant understand why or how this code works. Can someone explain it to me PLEASE?!? Ive got these cheeseburgers. No but fr, startTime is assigned the value of Date.now() which is like a trillion milliseconds right? I dont frickin GET IT

  • @AbduqodirRixsiboyev-i3f
    @AbduqodirRixsiboyev-i3f Рік тому

    ✨✨✨✨✨✨✨✨

  • @OgodoTejiriTreasureMoyo
    @OgodoTejiriTreasureMoyo 3 місяці тому

    See this code you post here is not working I did every single thing but your dad code is not working

  • @itzankan7893
    @itzankan7893 2 роки тому

    heart me

  • @kmdoll
    @kmdoll 2 роки тому +2

    yo bro. just wondering how would you add a resume button to this? i've been tinkering with it and i managed to somewhat add it. is there a way to make it better? thanks!
    startBtn.addEventListener("click", ()=>{
    if(paused){
    paused = false;
    startTime = Date.now();
    intervalId = setInterval(updateTime, 1000);
    }
    })
    pauseBtn.addEventListener("click", ()=>{
    if(!paused){
    paused = true;
    elapsedTime = Date.now() - startTime;
    clearInterval(intervalId);
    pauseBtn.style.display = "none";
    resumeBtn.style.display = "inline";
    }
    })
    resumeBtn.addEventListener("click", ()=>{
    if(paused){
    paused = false;
    startTime = Date.now() - elapsedTime;
    intervalId = setInterval(updateTime, 1000);
    pauseBtn.style.display = "inline";
    resumeBtn.style.display = "none";
    }

    })
    resetBtn.addEventListener("click", ()=>{
    paused = true;
    clearInterval(intervalId);
    hrs = 0;
    mins = 0;
    secs = 0;
    startTime = 0;
    currentTime = 0;
    timeDisplay.textContent = "00:00:00";
    pauseBtn.style.display = "inline";
    resumeBtn.style.display = "none";
    })
    function updateTime(){
    elapsedTime = Date.now() - startTime;
    secs = Math.floor((elapsedTime/1000) % 60);
    mins = Math.floor((elapsedTime/(1000 * 60)) % 60);
    hrs = Math.floor((elapsedTime/(1000 * 60 * 60)) % 60);
    secs = pad(secs);
    mins = pad(mins);
    hrs = pad(hrs);
    timeDisplay.textContent = `${hrs}:${mins}:${secs}`
    function pad(unit){
    return (("0")+unit).length > 2 ? unit : "0" + unit;
    }
    }

    • @notsorry4735
      @notsorry4735 2 роки тому +1

      Why do you have a resume button? Just add a
      document.getElementById("startBtn").textContent = "Resume"
      at the end of your paused if statement and add a
      document.getElementById("startBtn").textContent = "Start"
      at the end of your start button if statement. All it does is change the text on the start button and its only 2 lines of extra code

    • @iitzrohan
      @iitzrohan Рік тому

      After the if statement in pauseBtn, Write an else statement like this
      else {
      document.getElementById("pauseBtn").textContent = "Pause"
      paused = false;
      startTime = Date.now() - elapsedTime;
      intervalId = setInterval(updateTime, 1000);
      }

  • @TredecillionFan
    @TredecillionFan Рік тому +1

    hrs = Math.floor((elapsedTime / (1000 * 60 * 60)) % 24); Would be like this otherwise it is not working.

  • @lequangnghi194
    @lequangnghi194 2 роки тому +1

    Can anyone walk me through these lines of code?
    I don't get the hang of it AT ALL🥲
    startTime = Date.now() - elapsedTime;
    elapsedTime = Date.now() - startTime;

    • @kingsleyanyichie5630
      @kingsleyanyichie5630 Рік тому +1

      Hello bro even me I don't understand those startTime and elapsedTime

    • @TredecillionFan
      @TredecillionFan Рік тому +1

      startTime: This variable stores the timestamp (in milliseconds) when the timer is started or resumed. When the start button is clicked, the startTime is set to the current timestamp using Date.now(). When the timer is resumed after being paused, the startTime is updated to the timestamp at which the timer was paused plus the duration of the pause period, calculated as Date.now() - startTime.
      elapsedTime: This variable stores the amount of time (in milliseconds) that has elapsed since the timer was started or resumed. It is calculated as Date.now() - startTime.
      By subtracting the startTime from the current time, we can calculate the amount of time that has passed since the timer was started or resumed. This allows us to display the current time in the timer. For example, if the startTime is 10000 (representing 10 seconds), and the current time is 20000 (representing 20 seconds), then the elapsedTime would be 10000 (representing 10 seconds).
      I hope that helps! Let me know if you have any other questions.

    • @pav4540
      @pav4540 Рік тому

      @@TredecillionFan Thanks this cleared it up. But for some reason my count is not starting in my code. The button event listeners work. The timer function works, but it doesn't update the time display. The .js and .html script are interlinked too

  • @manueldiegoalexander3879
    @manueldiegoalexander3879 Рік тому

    Thanks bro