JavaScript countdown with css circles

732 views Asked by At

I have a countdown I am trying to have a visual display with css circles of the count down. But I cant figure out what to do to take away one circle at a time. My code duplicates the number of circles each loop. I know why, but what can I now do to get it to take one away each time?

JS Fiddle: http://jsfiddle.net/L0o9jmw9/

JS:

        var sec = 5
        function setClock() {
            var totalSec =  sec--;
            var s = parseInt(totalSec % 60, 10);
            var result = s + " seconds to go!";
            document.getElementById('timeRemaining').innerHTML = result;
            if(totalSec === 0){
                document.getElementById('timeRemaining').innerHTML = 'time out';
            }else{
                for(var i = 0; i < s; i++){
                    //console.log(i);
                    $('.cont-s').prepend('<div class="cir-s"></div>');
                }
                setTimeout(setClock, 1000);
            }
        }
        setClock();

HTML:

<div id="timeRemaining"></div>
<div class="cont-s"></div>

CSS:

.cir-s{
    width: 20px;
    height: 20px;
    background: #802A2A;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
    float:left;
}
1

There are 1 answers

0
Tom On BEST ANSWER

Simply empty the HTML before each iteration:

function setClock() {
    $('.cont-s').empty(); // empty the circles div

    var totalSec =  sec--;
    var s = parseInt(totalSec % 60, 10);
    var result = s + " seconds to go!";

    document.getElementById('timeRemaining').innerHTML = result;

    if(totalSec === 0){
        document.getElementById('timeRemaining').innerHTML = 'time out';
    } else {
        for(var i = 0; i < s; i++){
            $('.cont-s').prepend('<div class="cir-s"></div>');
        }
        setTimeout(setClock, 1000);
    }
}