gpt4 book ai didi

javascript - 如何每周显示数组中的一项

转载 作者:行者123 更新时间:2023-12-03 04:25:58 25 4
gpt4 key购买 nike

我正在尝试创建一个每周背诵经文的程序。我有代码来显示该项目,但只有延迟一段时间,无论我希望代码在更改项目之前等待多久。如何在数组中一次显示一个项目一周,然后继续显示下一个项目,而无需等待一周的延迟?这就是我现在拥有的:

<p id="wfm"></p>

var mind = [];
var i = 0;

var wfmind = document.getElementById('wfm');
function next_verse() {

wfmind.innerHTML = mind[i % mind.length];
i += 1;

}
setInterval(next_verse, 1000);

最佳答案

您可以使用当前时间作为索引,该索引从 1970 年开始计算,而不是用户进入网站的任意时间。

截至撰写本文时,当前时间戳为 1493684749486。

var d = new Date();
// +d === 1493684749486

要将当前时间戳转换为数组索引,您需要知道一周的毫秒数(1000*60*60*24*7),然后算出自 1970 年以来已经过去了多少周。

var index = Math.floor(+d / (1000*60*60*24*7));
// 2469 weeks have passed since 1970
// output `mind[index]` now.

为了此处的答案,我假设您想在周五上午 9 点更改该项目。下一个最接近的周五上午 9 点是 1494000000000。

d.setMilliseconds(0);
d.setSeconds(0);
d.setMinutes(0);
d.setHours(9);
d.setDate(d.getDate() + (7 + 5 - d.getDay()) % 7); // How many days away is Friday from Monday? Add that to the current date.

那是 315250514 毫秒。您将设置超时这么长的时间来开始下一次更改。

当项目发生更改时,为以下更改启动新的超时。这比 setInterval 更可取。

function displayNextItem() {
var d = new Date();
var timestamp = +d;
var index = Math.floor(timestamp / (1000*60*60*24*7));
wfmind.innerHTML = mind[index % mind.length];

d.setMilliseconds(0);
d.setSeconds(0);
d.setMinutes(0);
d.setHours(9);
d.setDate(d.getDate() + (7 + 5 - d.getDay()) % 7); // How many days away is Friday from Monday? Add that to the current date.

setTimeout(displayNextItem, +d - timestamp);
}
displayNextItem();

关于javascript - 如何每周显示数组中的一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43728287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com