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:
But when I let the script run and log to the console I get 3 minutes added on as well as the seconds:
Is there a weird javascript timing thing that I'm missing here?
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=/`;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With