Skip to main content

How do I put a live time(seconds) counter on a page?

Javascript • Asked by Arjun Rajkumar
As in it should go 00:00 .. 00:05.. 00.49 ..15:55 to whatever. 
Wondering how to do this on the front-end.

Should I just use jquery? Or something else? 
Any suggestions?

Thanks

Arjun

Hi Arjun,

You could use normal JS with the setInterval method. Something like this: 

function timer(seconds){
    clearInterval(countdown);
    displayRemainingTime(seconds);
    const then = Date.now() + seconds * 1000;
    countdown = setInterval(() => {
        const secondsLeft = Math.round((then - Date.now()) / 1000);
        if(secondsLeft < 0) {
            clearInterval(countdown);
            return;
        }
        displayRemainingTime(secondsLeft);
    }, 1000)
}

function displayTimeLeft(){
 //update dom
}


I did something like this as part of a Javascript 30 course by Wes Bos. Recommend checking it out

William


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.