Link to home
Start Free TrialLog in
Avatar of Isaiah Melendez
Isaiah Melendez

asked on

Javascript Help: Timer

Hello, Experts,

I am building a countdown timer (code below):

let winner = "John Doe";

//creates a function and stores the function inside a variable
var add_minutes = function(dt, minutes) {
    return new Date(dt.getTime() + minutes*60000);
};

var currentTime = new Date();
var futureTime = add_minutes(currentTime,5);

var difference = futureTime.getTime() - currentTime.getTime();

console.log(difference);

var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((difference % (1000 * 60)) / 1000);

var x = setInterval( function() {

        document.getElementById("clock").innerHTML =  minutes + "m " + seconds + "s ";

        if (difference < 0) {
            clearInterval(x);
            document.getElementById("clock").innerHTML = "Test: " + winner;
    }

    }
    ,1000);

Open in new window


and ref'ing it/attaching to a HTML file (below)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p id="clock"></p>
</body>
<script src="test.js"></script>
</html>

Open in new window


And the timer does not count down. Any idea why this might be the case?

User generated image
Avatar of zc2
zc2
Flag of United States of America image

You need something which would modify the difference variable
Also formatting to minutes/seconds should be done on each count, thus be inside the interval handler's function.

let winner = "John Doe";

//creates a function and stores the function inside a variable
var add_minutes = function(dt, minutes) {
    return new Date(dt.getTime() + minutes*60000);
};

var currentTime = new Date();
var futureTime = add_minutes(currentTime,5);

var difference = futureTime.getTime() - currentTime.getTime();

console.log(difference);


var x = setInterval( function() {
console.info("difference:" + difference);
        var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((difference % (1000 * 60)) / 1000);
        document.getElementById("clock").innerHTML =  minutes + "m " + seconds + "s ";
	 difference -= 1000;    // added this line
        if (difference < 0) {
            clearInterval(x);
            document.getElementById("clock").innerHTML = "Test: " + winner;
    }

    }
    ,1000);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of zc2
zc2
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Isaiah Melendez
Isaiah Melendez

ASKER

thanks zc2 that did it. I appreciate the help.