Search code examples
javascriptdatedateadd

javascript add minutes to new Date(); before using the object


I have a function calls that start a bunch of timers and I want to add a few minutes to each one so they don't all start off at zero. I had success with:

var currentDate = new Date();
var twentyMinutesLater = new Date(currentDate.getTime() + (20 * 60 * 1000));
new CountUp(twentyMinutesLater, 'counter03');

I would love to skip creating the var twentyMinutesLater and so on for all the timers I want, I just can't get the syntax right, or maybe it's not possible. Is there a way to add the milliseconds that in the function call below.

new CountUp(new Date(), 'counter03');

I've tried:

new CountUp((new Date() + (20 * 60 * 1000)), 'counter03');

Result NaN NaN:NaN:NaN so it's not a number Same result with double quotes.

Any javascript syntax masters out there that have any ideas?


Solution

  • In your specific code, you're passing a Date object to the counter code and that is not what it is expected. It is expecting a time value from which it will make it's own Date object (you can see that right in the constructor for the Counter function). Plus, the counter code won't take times in the future, only times in the past (perhaps because it doens't want to deal with negative times - I don't know).

    Here's a working example here where I've modified my other jsFiddle used in the answer to your other question.

    function addCounter() {
        var currentDate = new Date();
        var twentyMinutesLater = currentDate.getTime() - (20 * 60 * 1000);
        var div = document.createElement("div");
        div.id = "counter" + counterNum++;
        document.body.appendChild(div);
        new CountUp(twentyMinutesLater, div.id);
    }
    

    And, here's a jsFiddle that lets you enter a number of minutes and it will start a counter at that value: http://jsfiddle.net/jfriend00/vnf5z/.