javascript cookie expire in 5 minutes

If you want to set a JavaScript cookie that expires in 5 minutes, there are a few different ways you can do it. Here are three possible solutions:

Solution 1: Using the Date Object

You can create a new Date object and set its time to the current time plus 5 minutes. Then you can use the toUTCString() method to convert the date to a string that can be used as the cookie's expiration time.


let expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() + (5 * 60 * 1000));
let expirationString = expirationDate.toUTCString();

document.cookie = "myCookie=myValue; expires=" + expirationString;

Solution 2: Using the setMinutes() Method

You can also use the setMinutes() method of the Date object to set the expiration time to 5 minutes from the current time. This method automatically adjusts for changes in date and time, such as daylight saving time.


let expirationDate = new Date();
expirationDate.setMinutes(expirationDate.getMinutes() + 5);

document.cookie = "myCookie=myValue; expires=" + expirationDate.toUTCString();

Solution 3: Using the setTimeout() Method

Another option is to use the setTimeout() method to create a function that sets the cookie after 5 minutes have passed. This method can be useful if you need to perform some other actions before setting the cookie.


function setCookie() {
  document.cookie = "myCookie=myValue";
}

setTimeout(setCookie, 5 * 60 * 1000);

These are three possible solutions for setting a JavaScript cookie to expire in 5 minutes. You can choose the one that best suits your needs and implement it in your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe