每天运行一次代码

3 javascript loops

我只是想知道是否有可能有一个javascript for循环只能每天迭代一次循环,即日期更改?

for(i=0; i < myArray.length; i++){

    alert(myArray[i]);

}
Run Code Online (Sandbox Code Playgroud)

所以在上面的循环中,让它运行,并冻结它或只是一些东西,直到数据发生变化,再做一次迭代,然后继续这样做......你知道我的意思.

提前致谢!

vsy*_*ync 10

当你没有服务器时,使用localStorage是最好的方法,因为javascript代码可能会重新启动(通过关闭选项卡并重新打开),因此会丢失之前的状态.

下面的方法更加防弹:

// 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
Run Code Online (Sandbox Code Playgroud)