Search code examples
timercountdownonscroll

How to create a timer that starts at 10 and goes to 1 in 3 seconds?


I am a web designer, and I am not much of a developer. I need to create a timer that counts down quickly from 10 to 1 when a user scrolls to the part of the page where that div appears. I'm planning on using a large bold font with nothing but "10" in it, that scrolls through the numbers 9-2 and then stops at 1. (ie, I don't need a timer that also has hours, colons, or minutes.

Anyone have any ideas? Thank you ahead of time!!!!


Solution

  • This is done with simple javascript and one span element.

    var number = 10;
    var counter = document.getElementById('counter');
    function countDown() {
       counter.innerHTML = '' + number;
       number--;
       if(number > 0) {
          setTimeout(function() { countDown(); }, 1000.0/3);
       }
    }
    countDown();
    <span id="counter"></span>

    That will trigger counter after it pops into visible part of the screen on scroll. Note that I've added two items, just for testing purpose.

    var elements = {
        counterA: {
                from: 10,
                to: 0,
                counterStarted: false,
                dom: document.getElementById('counterA'),
                speed: 1000.0/3
        },
        counterB: {
                from: 400,
                to: 49,
                counterStarted: false,
                dom: document.getElementById('counterB'),
                speed: 1000.0/40
        }
    };
    
    function countDown(el) {
        el.dom.innerHTML = '' + el.from;
        el.from--;
        if(el.from > el.to) {
                setTimeout(function() { countDown(el); }, el.speed);
        }
    }
    
    function triggerCounterIfVisible(el) {
        if(el.counterStarted) return;
    
        var elemTop = el.dom.getBoundingClientRect().top;
        var elemBottom = el.dom.getBoundingClientRect().bottom;
    
        var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
        if (isVisible) {
                el.counterStarted = true;
                countDown(el);
        }
    }
    
    window.onscroll = function() {
        for(var el in elements) {
                triggerCounterIfVisible(elements[el]);
        }
    };
    <div style="height: 3000px"></div>
    <hr />
    <p>Counter: <span id="counterA"></span></p>
    
    <div style="height: 3000px"></div>
    <hr />
    <p>Counter: <span id="counterB"></span></p>
    
    <div style="height: 3000px"></div>