JS 一天执行一次的方法

一天执行一次,很常用的场景,思路就是利用一个标识,今天没有这个标识就执行操作,然后添加标识,后续判断标识存在就不再执行相应的操作。具体实现是添加一个cookie,第一次没有这个cookie,就执行操作,同时添加一个到第二天凌晨过期的cookie。

代码如下:

function DoOne(key,method) {
	var v = getCookie(key);
	if (!v) {
		method("do something");
		//获取第二天凌晨到当前时间的秒数
		var tim_sec = 24 * 60 * 60 - (new Date().getHours() * 60 * 60 + new Date().getMinutes() * 60 + new Date().getSeconds());
		setCookie(key, "1", tim_sec);
	}
}
function dosome(msg){
	console.log(msg);
}
//写cookies 
function setCookie(name, value, second) {
	if (!second) {
		second = 7 * 24 * 60 * 60;//默认7天
	}
	var exp = new Date();
	exp.setTime(exp.getTime() + second * 1000);
	document.cookie = name + "=" + encodeURI(value) + ";expires=" + exp.toGMTString() + ";path=/";
}
//读取cookies 
function getCookie(name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(name + "=");//获取字符串的起点
		if (c_start != -1) {
			c_start = c_start + name.length + 1;//获取值的起点
			c_end = document.cookie.indexOf(";", c_start);//获取结尾处
			if (c_end == -1) c_end = document.cookie.length;//如果是最后一个,结尾就是cookie字符串的结尾
			return decodeURI(document.cookie.substring(c_start, c_end));//截取字符串返回
		}
	}
	return "";
}

调用:

DoOne("key", dosome);

结果,每天第一次打开这个页面时都会输出

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值