且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

每天运行一次代码

更新时间:2023-02-25 14:56:25

使用

Using localStorage is the best way to go when you don't have a server, since the javascript code might restarted (by closing the tab and re-opening), therefore loosing the previous state.

// 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