Run code once a day

后端 未结 3 1519
南旧
南旧 2020-12-06 14:45

I was just wondering if it is possible to have a javascript for loop that only iterates through the loop once a day i.e. when the date changes?

for(i=0; i &l         


        
3条回答
  •  广开言路
    2020-12-06 15:29

    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.

    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
    

提交回复
热议问题