简体   繁体   English

我每天如何在javascript中加载一次运行函数?

[英]How would I run a function on load in javascript once per a day?

Let's say it's June 18 and a person runs the javascript and it runs a function on load but it doesn't run the function later that day even if the person closes the window or program in my case. 假设是6月18日,一个人运行了javascript,并在加载时运行了一个函数,但是即使那天我关闭了窗口或程序,它也不会在当天晚些时候运行该函数。 However, on June 19 if the person opens the program and it runs the javascript then it runs the function because it's a new day and hasn't run that day yet... So basically, how do I make an onload function only work once per a day? 但是,在6月19日,如果该人打开程序并运行javascript,则它将运行该函数,因为这是新的一天,而且还没有那天运行。所以,基本上,我如何使onload函数仅能运行一次每天? It has to be javascript because the program I'm using can only be assisted by javascript files and nothing else. 它必须是javascript,因为我正在使用的程序只能由javascript文件辅助,而没有别的。 The person has to download the files to their computer so how would I go about saving and retrieving the localStorage? 这个人必须将文件下载到他们的计算机,所以我该如何保存和检索localStorage?

You can use localStorage to achieve this. 您可以使用localStorage实现此目的。 Sample Code: 样例代码:

/* returns null if local storage is not defined */
var localVal = localStorage.getItem('someUniqueName'); 

if(localVal  == null){ 
    // execute the function
}else{
    var tempd = new Date();
    var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
    if(localVal.localeCompare(str) == -1){
        //execute function
        localStorage.setItem('someUniqueName',str);
    }
}

If you wish to create a cookie and handle it, then you may go through this question 如果您想创建一个cookie并进行处理,那么您可能会遇到这个问题

You can create a cookie on the user's browser that persists till the end of the day. 您可以在用户的​​浏览器上创建一个cookie,该cookie一直持续到一天结束。 If you are using jQuery, you can do as follows ( taken from here ): 如果您使用的是jQuery,则可以执行以下操作(从此处获取 ):

var currentDate = new Date();
expirationDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()+1, 0, 0, 0);
$.cookie("ultOS", "5", {expires: expirationDate});

If you are using plain javascript, then the way to do this would be as follows (from here ): 如果您使用的是普通的javascript,那么执行此操作的方法如下(从此处开始 ):

  function createCookie(name,value,date) {
        if (date) {
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }

var today = Date();
var midnight = today.getDate()+1
midnight.setHours(0,0,0,0);
createCookie("Valid","true",midnight);

At the beginning of every page load, just check the value of this cookie. 在每次页面加载开始时,只需检查此cookie的值即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM