A stopwatch written in JavaScript ⏱️

Поделиться
HTML-код
  • Опубликовано: 28 дек 2024

Комментарии • 73

  • @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 3 месяца назад

      bro's github is yt comments

    • @hacksark9748
      @hacksark9748 20 дней назад

      i dont understand why using miilisecond

  • @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

  • @tn11_deadpool87
    @tn11_deadpool87 2 года назад +4

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

  • @icy_invader
    @icy_invader Год назад +1

    you very best bro 😁 thankyou for this tutorial 😊

  • @anonimanonim1223
    @anonimanonim1223 2 года назад +1

    Very good videos

  • @ViolettaNjombwa
    @ViolettaNjombwa 9 месяцев назад

    This has made things for me more easier ❤

  • @shreehari2589
    @shreehari2589 2 года назад +2

    Really loving these mini projects, thanks bro

  • @малосольные-окурки
    @малосольные-окурки 7 месяцев назад

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

  • @akshayav1035
    @akshayav1035 Год назад

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

  • @khalidelgazzar
    @khalidelgazzar 7 месяцев назад

    Great tutorial thank you

  • @markmcla
    @markmcla 2 года назад

    Thanks for sharing this! Your example is very helpful.

  • @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 RUclips

    • @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

  • @PrankIncluded
    @PrankIncluded 2 года назад

    Osm video ❤️

  • @sainy1048
    @sainy1048 2 года назад

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

  • @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!

  • @popo12-c5d
    @popo12-c5d 2 года назад

    you are great

  • @NOTHING-en2ue
    @NOTHING-en2ue Год назад

    you're amazing man ❤

  • @pav4540
    @pav4540 Год назад

    Thanks bro

  • @lucabinder9829
    @lucabinder9829 2 года назад

    Nice one!

  • @marxLz
    @marxLz 2 года назад

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

  • @AbduqodirRixsiboyev-i3f
    @AbduqodirRixsiboyev-i3f Год назад

    thank you bro

  • @kaolin-x4790
    @kaolin-x4790 2 года назад

    My bro I need more javaScript projects.

  • @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: ruclips.net/p/PLZPZq0r_RZOMRMjHB_IEBjOW_ufr00yG1

  • @vicentenitti4141
    @vicentenitti4141 10 месяцев назад

    "secs = 0"
    Me too pal.

  • @AyomideYusuf-jv2mm
    @AyomideYusuf-jv2mm 3 месяца назад +1

    Secs 🤔🤔

  • @LFF5644
    @LFF5644 Год назад +1

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

  • @bomapdich
    @bomapdich Год назад

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

  • @DavidR212
    @DavidR212 Год назад

    thank you so much

  • @vasanthkumar.r2700
    @vasanthkumar.r2700 Год назад +1

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

  • @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);
      }

  • @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)

  • @bLitzKinG20
    @bLitzKinG20 2 года назад

    Thanks man!

  • @fr1endsies
    @fr1endsies 2 года назад

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

  • @rudrarajkar1116
    @rudrarajkar1116 2 года назад

    is this what consistency is?

  • @sagidkhair98
    @sagidkhair98 2 года назад

    Bro ... can u make an ecom website tutorial

  • @AbduqodirRixsiboyev-i3f
    @AbduqodirRixsiboyev-i3f Год назад

    ✨✨✨✨✨✨✨✨

  • @limu3749
    @limu3749 Год назад

    What is the use of let currentTime = 0?

    • @time0psy
      @time0psy 10 месяцев назад

      Here, no use. Maybe meant for later.

  • @augischadiegils.5109
    @augischadiegils.5109 2 года назад

    ❤️❤️❤️❤️

  • @clrkkdd12
    @clrkkdd12 2 года назад +1

    👊🏽

  • @lyon8539
    @lyon8539 Год назад

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

  • @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

  • @nayabshaik7702
    @nayabshaik7702 2 года назад

    Bro please do some small projects in python

  • @nadicadizdarevic2835
    @nadicadizdarevic2835 12 дней назад

    hours...Math.floor(elapsedTime/(60*60*1000) );
    mins...Math.floor(elapsedTime/(60*1000));
    sec..Math.floor(elapsedTime/1000);
    Why you added % ?

  • @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

  • @OgodoTejiriTreasureMoyo
    @OgodoTejiriTreasureMoyo 4 месяца назад

    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

  • @user-fz1cj8rh6k
    @user-fz1cj8rh6k 2 года назад +1

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

  • @TredecillionFan
    @TredecillionFan Год назад +2

    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 2 года назад +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