Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date.setSeconds working as expected in Debugger but not in script

I have a function that sets a cookie as follows:

function createCookieWithDuration(name, value, duration) {
    const date = new Date();
    console.log(`date now: ${date}`);
    date.setSeconds(date.getSeconds() + duration);
    console.log(`adjusted date by ${duration} seconds: ${date}`);
    document.cookie = `${name}=${value}; expires=${date}; path=/`;
}

Now, if I do this line for line in the debugger it works as expected: enter image description here

But when I let the script run and log to the console I get 3 minutes added on as well as the seconds:

enter image description here

Is there a weird javascript timing thing that I'm missing here?

like image 220
rory Avatar asked Nov 06 '22 21:11

rory


1 Answers

Use this code, but make sure that duration is in miliseconds, so if you want to add 2 seconds you need to pass 2000, or if you're passing seconds just add duration * 1000 in code.

function createCookieWithDuration(name, value, duration) {
    const date = new Date();
    console.log(`date now: ${date}`);
    const newDate = new Date(date.getTime() + duration);
    console.log(`adjusted date by ${duration}: ${newDate}`);
    document.cookie = `${name}=${value}; expires=${newDate}; path=/`;
}
like image 77
N.Tasikj Avatar answered Nov 15 '22 06:11

N.Tasikj