我正在尝试每天减少一次变量。我为此编写了以下代码。
var counter = 10; //any value
setInterval(function() {
counter = counter - 1;
}, 86400000);
是否有更好或更有效的方法来实现同样的目标?
P.S: - 我不想使用任何库。
答案 0 :(得分:2)
我没有看到你写它的方式有任何问题。你使用间隔,好吧,但这不是你可能做设置变量值的最坏的罪恶。
您可能会想到另一个带有函数的解决方案,该函数会返回当前计数器。
var initialValue = 20000;
function getCounter() {
return initialValue - Math.floor(Date.now() / 1000 / 60 / 60 / 24);
}
console.log(getCounter());
不同之处在于它从UNIX时间开始需要当前的日期编号。每天都会增加日期编号,因此函数的结果将减少1。
但我仍然没有看到这个解决方案如何比你的更好。
答案 1 :(得分:1)
我唯一看到你错过的是设置counter
变量的初始值
我会写:
var counter = 1000; // or any useful value
setInterval(function() {
--counter;
}, 24 * 60 * 60 * 1000); // this is more self-explanatory than 86400000, and, being evaluated just once, it will have a tiny effect on the performace of the script
答案 2 :(得分:0)
我不完全确定原因,但使用setInterval
这样会让我感到不舒服。
如果我要求这样做,我会使用类似这样的方法:
var counter = 10;
var timeout = new Date();
setInterval(function(){
if(new Date() >= timeout)
{
--counter; // the action to perform
timeout = new Date(timeout.getTime() + 86400000); // update the timeout to the next time you want the action performed
}
console.log(counter);
},1000); // every second is probably way more frequent than necessary for this scenario but I think is a decent default in general
这允许的一件事是,例如,将下一个超时设置为明天的午夜,而不是被锁定到自上次执行以来的X秒内#34;。关键是控制反转 - 行动本身现在可以决定下一次运行的时间。
虽然我可能会抽象接受开始,间隔和操作的界面背后的细节。
答案 3 :(得分:0)
也许使用window.localStorage保存最后一次,如果它大于60 * 60 * 24(一天中的秒数),将最后一次设置为今天上午/现在/ 1:00,然后减小值,保存它。
示例:
var d = new Date();
var mins = -(1+d.getHours())*60+d.getMinutes();
var secs = mins*60+d.getSeconds(); // total seconds passed today from 1:00
var now = d.getCurrentTime():
var lastCheck = localStorage.getItem("lastCheck");
if (!lastCheck)
{
localStorage.saveItem("lastCheck",now-secs); // beginning of today
}
var dayPassed = now - lastCheck > 24*60*60; // change to see if a day has passed
if (dayPassed)
{
// save seconds
localStorage.setItem("counter",localStorage.getItem("counter")-1);
localStorage.saveItem("lastCheck",now-secs); // beginning of today
}
答案 4 :(得分:0)
我眼中最大的问题是你必须让这个JS流程一直运行几天才能让它完成你所需要的工作。世界并不是那么完美,以至于事情不需要偶尔重启......包括普通的JS流程。
就个人而言,我会存储我的起点的时间戳,然后(每当我需要知道已经过了多少时间)时,抓住一个新的时间戳并用它来计算它已经过了多少天。这样即使某些事情中断了我的过程,我仍然可以在我开始的地方。
答案 5 :(得分:-2)
让我更有意义的是检查自特定日期起已经过了多少天,并减少来自柜台的天数。主要是因为我不希望任何人在没有需要的情况下打开同一页面,或者想要连续几天重新加载。我会做这样的事情:
counter = 365; // original counter
var start = new Date(2016, 03, 20); // original date
var now = new Date();
var days = Math.floor(Math.abs(start.getTime()-now.getTime())/(24*60*60*1000))
counter -= days;
这样每次访问该页面时,它都会正确递减。请注意,这会忽略闰日或时区的任何问题。上面的例子对我来说有一个360的计数器。然后,如果您确实希望它开放数天,请使用以下命令自动重新加载:
self.setTimeout(function(){document.location.reload()}, 86400000);