skip to Main Content

I have a countdown timer on my website, and I want it to overlay a generic explosion GIF when the timer runs out. I have a function call when it runs out, now I just need to know what will go in that function.

I’m really new to JavaScript and web dev as a whole, so I don’t have any idea how to go about this.

I’ve tried looking online but all of the docs I’ve found don’t provide any help or don’t make any sense.

This is the code that I have so far:

window.onload = function () {
    var time = 299, // your time in seconds here
        display = document.querySelector('#timer');
    startTimer(time, display);
};

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            
            // This is the part that will call the explosion function.
        }
    }, 1000);
}

6

Answers


  1. nice job setting up the timer! to overlay an explosion GIF when the timer runs out, you just need to add an image element with the GIF and style it to appear over the content when the countdown hits 0.

    1. add the explosion GIF to your HTML, but keep it hidden at first:
    <img id="explosion" src="your-explosion.gif" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999;" />
    1. in your JavaScript, modify the part where the timer reaches 0 to show the GIF:
    if (--timer < 0) {
        document.getElementById('explosion').style.display = 'block';
    }

    so, your updated startTimer function will look something like this:

    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);
    
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;
    
            display.textContent = minutes + ":" + seconds;
    
            if (--timer < 0) {
                // show the explosion gif
                document.getElementById('explosion').style.display = 'block';
            }
        }, 1000);
    }

    this will make the GIF take over the whole screen when the timer hits 0. Let me know if it works

    Login or Signup to reply.
  2. It can be achieve by many ways but simplest is by creating a html div with some class or id and inside that div add image/video/gif of your explosion and set it to display: none; and whenever we want to show the explosion, set the display to block/flex as per your need.

    Below is working example. Your counter also working in negative values, I haven’t fixed it by thinking it might be intentional.

    window.onload = function() {
      var time = 10, // your time in seconds here
        display = document.querySelector('#timer');
      startTimer(time, display);
    };
    
    function startTimer(duration, display) {
      var timer = duration,
        minutes, seconds;
      if (timer > 0) {
    
        setInterval(function() {
    
          minutes = parseInt(timer / 60, 10)
          seconds = parseInt(timer % 60, 10);
    
          minutes = minutes < 10 ? "0" + minutes : minutes;
          seconds = seconds < 10 ? "0" + seconds : seconds;
    
          display.textContent = minutes + ":" + seconds;
    
          if (--timer < 0) {
            document.querySelector(".explosionDiv").style.display = "flex";
          }
        }, 1000);
      }
    
    }
    body {
      background-color: white;
      color: black;
      margin: 0;
      padding: 0;
    }
    
    .mainDiv {
      color: white;
      width: 100%;
      height: 100vh;
      background-color: white;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .explosionDiv {
      display: none;
      background-color: black;
      color: white;
      position: absolute;
      top: 0;
      width: 100%;
      height: 100vh;
      align-items: center;
      justify-content: center;
      z-index: 10;
    }
    <h2 id="timer">
      Clean Code Editor
    </h2>
    
    <div class="explosionDiv">
      Explosion Image/Video/gif here
    </div>
    Login or Signup to reply.
  3. Assuming that the gif is inside a <img> element and has its id attribute set to "elementId", you can do the following to display the gif:

    function displayExplosion() { 
      document.getElementById('elementId').style.display = 'block';
    }
    

    Also, be sure to handle your timer, i.e, reset it or clear it. Have a look at this for more info.

    To learn more about the display css property, visit: https://developer.mozilla.org/en-US/docs/Web/CSS/display

    Login or Signup to reply.
  4. so you can use ClearInterval() and need to change some code.

    var countDown = setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);
    
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
    
        display.textContent = minutes + ":" + seconds;
    
        if (--timer < 0) {
                
            // This is the part that will call the explosion function.
            ClearInterval(countDown);
            // Please call a callback function here.
        }
    }, 1000);
    
    Login or Signup to reply.
  5. You should create an element as overlay in HTMl with position: fixed; inset: 0; and hide it by default. You then can use in JS classList.remove() to remove the class that hides the overlay so it will be visible.

    You need to stop the interval if the time reaches 0 with clearInterval.

    I also refactored your code:

    window.addEventListener('DOMContentLoaded', function() {
      startTimer();
    })
    
    function startTimer() {
      let time = 30; // reduced the timer for demo reasons
      const timerIntervall = setInterval(function () {
        let minutes = twoDigitNumber(parseInt(time / 60));
        let seconds = twoDigitNumber(time % 60);
    
        timer.value = `${minutes}:${seconds}`;
        time--;
        
        if (time === 0) {
          overlay.classList.remove('d-none');
          clearIntervall(timerInterval);
        }
      }, 1000);
    }
    
    function twoDigitNumber(number) {
      return number.toString().padStart(2,0);
    }
    #overlay {
      position: fixed;
      inset: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      &.d-none {
        display: none;
      }
    }
    <body>
      <div id="overlay" class="d-none">
        <img src="https://placehold.co/600x400">
      </div>
      
      <output id="timer"></output>
    </body>

    Refactor Informations

    You should not use on events such as onload. Those events can only exist once and they will overwrite each other. It might not seem important in your "little" project but it will teach you wrong habits. You should always use addEventListener to append events. That way you will not overwrite other events that might have been added. A common reason for an unintentional overwriting of an event is another script often written by other programmers.

    You should and do not need to hand over parameters all the time. The only place where this might happen is with the usage of a config file. In that case you should not use ladder logic but object-oriented programming using Class.
    With the ladder logic you used, you should have the time variable (actually a let not a var) inside your discrete function. Same for the element which should be a const! However, referencing that element is not needed as you can call elements on their id directly in ES6.

    Do not write repetitive code such as:

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    

    Instead, write a discrete function.

    if (--timer < 0) { ... }
    

    This is hardly readable as it is easy to miss your decrementing. You write code not for machines but to be readable for other humans. So write longer code if it makes the code more readable and try not to hide simple things instead of writing them into a new line!

    display is a method in JS. it is not a suitable name for a variable to constant. Besides that, it is not an intuitive name for a timer. Always choose meaningful names that explain what the name is used for.

    Login or Signup to reply.
  6. <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Countdown Timer</title>
        <style>
            #explosion {
                display: none;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                z-index: 1000; /* Make sure it overlays other content */
            }
            #timer-container {
                position: relative;
                width: 100%;
                height: 100vh;
            }
        </style>
    </head>
    <body>
        <div id="timer-container">
            <div id="timer"></div>
            <img id="explosion" src="path/to/your/explosion.gif" alt="Explosion">
        </div>
        <script src="path/to/your/script.js"></script>
    </body>
    </html>
    
    
    <script>
        window.onload = function () {
            var time = 299, // your time in seconds here
                display = document.querySelector('#timer');
            startTimer(time, display);
        };
    
        function startTimer(duration, display) {
            var timer = duration, minutes, seconds;
            var countdown = setInterval(function () {
                minutes = parseInt(timer / 60, 10);
                seconds = parseInt(timer % 60, 10);
    
                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;
    
                display.textContent = minutes + ":" + seconds;
    
                if (--timer < 0) {
                    clearInterval(countdown);
                    showExplosion();
                }
            }, 1000);
        }
    
        function showExplosion() {
            var explosion = document.getElementById('explosion');
            explosion.style.display = 'block';
        }
    
    </script>
    

    please refer the above code

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search