我有50-60本书短文的清单,我希望每天随机显示一本书(使用html / Javascript的某种组合)。我将如何做到这样,以便每24小时选择一次随机段落并将其显示在网站上?
我已经研究过setInterval,但不允许24小时。
答案 0 :(得分:0)
application/json
此功能每60秒发生一次,并在时间为00:00时在控制台中打印“重置”,
您应该保存用户打开网页的时间,并与现在进行比较,替换function timer_passage(){
var now = new Date()
if (0==now.getHours() && 0==now.getMinutes()){
console.log("reset")
//do something you want
}
setTimeout(timer_passage, 60000)//exec myself after 60000 ms
}
答案 1 :(得分:0)
var today= new Date();
function setTextAndTime(){
//Code To Set Text Here
localStorage.setItem("Timer",today.getTime());
}
if(!localStorage.getItem("Timer"))
{
localStorage.setItem("Timer",today.getTime());
}
else{
var lastSavedTime=localStorage.getItem("Timer");
var diffInTime = Math.abs(today.getTime()- lastSavedTime);
var diffInHours = Math.ceil(diffTime / (1000 * 60 * 60 ));
var idealIntervalTime=diffInHours>=24?0:diffInTime;
setInterval(function(){
setTextAndTime();
},idealIntervalTime);
}
如果该变量大于day的话,这将节省会话时间。并且将在60分钟内检查会话。
答案 2 :(得分:0)
如果我很了解您的需求,则可以使用浏览器的LocalStorage(或Cookie)。即使用户刷新页面,或关闭并重新打开页面,它也可以正常工作。
let funcDisplay = () => {
if (!localStorage.getItem('time_displayed') || new Date().getTime() - localStorage.getItem('time_displayed') >= 60000*24*60) // 60000 millisecondes * 24h * 60min
{
// Save LS time_displayed
localStorage.setItem('time_displayed', new Date().getTime());
// ...Your codes for displaying page... (Bonus : you could also use LocalStorage for saving array of displayed pages, if you want to avoid the same displayed pages)
window.setTimeout(funcDisplay, 60000*24*60); // after 24h, func display will re-execute
} else {
let in_diff_milisecondes = localStorage.getItem('time_displayed') + 60000*24*60 - new Date().getTime()
window.setTimeout(funcDisplay, in_diff_milisecondes) // after xxx milisecondes, func display will execute
}
}
希望它对您有帮助。