19

Could someone update the following code to make the cookie expire in 30 seconds.

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}
Odyssey
  • 263
  • 1
  • 2
  • 6
  • 3
    So... you've done a copy/paste off w3schools... Quirksmode has a better explanation of cookies in JavaScript: http://www.quirksmode.org/js/cookies.html – CD001 Oct 24 '11 at 18:07
  • What are you trying to do? Why do you want it to expire so quickly? – Jason Gennaro Oct 24 '11 at 18:08
  • 1
    @Jason There might be times when you simply want to pass data between pages without sending that information over the wire. In cases like that a quickly expiring cookie does a good job. – TyMayn Oct 03 '17 at 23:24

2 Answers2

35
function createCookie(name, value) {
   var date = new Date();
   date.setTime(date.getTime()+(30*1000));
   var expires = "; expires="+date.toGMTString();

   document.cookie = name+"="+value+expires+"; path=/";
}
evilone
  • 22,410
  • 7
  • 80
  • 107
9

You can specify the maximum age in seconds when setting a cookie:

function setCookie(name, value, maxAgeSeconds) {
    var maxAgeSegment = "; max-age=" + maxAgeSeconds;
    document.cookie = encodeURI(name) + "=" + encodeURI(value) + maxAgeSegment;
}

Usage:

setCookie("username", "blaise", 30);
Blaise
  • 13,139
  • 9
  • 69
  • 97