Skip to content
the poor coder

javascript cookie expire in 5 minutes

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

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.

Text

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.

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC