Run code once a day

Using localStorage is the best way to go when you don't have a server (because a user can change the computer's time and break your logic, and using a server it's harder to hack this)

Method below is more bulletproof:

// checks if one day has passed. 
function hasOneDayPassed()
  // get today's date. eg: "7/37/2007"
  var date = new Date().toLocaleDateString();

  // if there's a date in localstorage and it's equal to the above: 
  // inferring a day has yet to pass since both dates are equal.
  if( localStorage.yourapp_date == date ) 
      return false;

  // this portion of logic occurs when a day has passed
  localStorage.yourapp_date = date;
  return true;
}


// some function which should run once a day
function runOncePerDay(){
  if( !hasOneDayPassed() ) return false;

  // your code below
  alert('Good morning!');
}


runOncePerDay(); // run the code
runOncePerDay(); // does not run the code

If you want something to happen at predefined intervals, you can set a timeout/interval: http://www.w3schools.com/js/js_timing.asp

For example:

var dayInMilliseconds = 1000 * 60 * 60 * 24;
setInterval(function() { alert("foo"); },dayInMilliseconds );

edit: since you mentioned that the code will be running in a browser, this assumes the browser is running for at least 24 hrs and will not work otherwise.


the best way to achieve it is by creating a cookie that lasts for1 day.. Even if after the refresh of the web page or browser gets closed that countdown will still continue..

setcookie($cookie_name, $cookie_value, time() + 86400, "/"); 

This means 86400 = 1 day

Hope it helps