gpt4 book ai didi

javascript - Chrome 扩展程序 : how to set function to execute when day has changed

转载 作者:行者123 更新时间:2023-12-02 21:32:19 25 4
gpt4 key购买 nike

目前,使用我的 Chrome 扩展程序,我希望在用户新的一天开始时执行一段代码(用户可能有不同的时区)。我最初是在看这个answer但似乎已经过时了,并且对使用 Chrome API 来帮助我感到好奇。

我正在研究 chrome.events 和 chrome.alarms,但发现很难通读并找到我想要的内容。

到目前为止我的代码看起来像这样

background.js

const newDayExecute = () => {
// Code block to execute on a new day
}

setInterval(newDayExecute, 86400000 ) // execute block of code every 24 hours

最佳答案

如果用户重新启动浏览器或扩展因任何原因重新启动,则使用 setInterval()setTimeout() 将不起作用。 chrome.alarms API 也是如此。

由于用户很可能每天多次重新启动 Chrome,我建议您在 localStorage 中保存时间戳,然后使用 setInterval() 函数不断检查是否已达到该时间戳。这样,即使扩展程序或整个浏览器重新启动,您仍然可以检测到一天已经过去。

类似这样的事情:

function doSomething() {
// Code that needs to run every day here
}

function tick() {
// Re-calculate the timestamp for the next day
let next = new Date(Date.now() + 24 * 60 * 60 * 1000);

// Adjust the timestamp if you want to run the code
// around the same time of each day (e.g. 10:00 am)
next.setHours(10);
next.setMinutes(0);
next.setSeconds(0);
next.setMilliseconds(0);

// Save the new timestamp
localStorage.savedTimestamp = next.getTime();

// Run the function
doSomething();
}

function checkTimestamp() {
if (localStorage.savedTimestamp)
let timestamp = parseInt(localStorage.savedTimestamp);

if (Date.now() >= timestamp)
tick();
} else {
// First time running
tick();
}
}

// Check every minute
setInterval(checkTimestamp, 60000);

关于javascript - Chrome 扩展程序 : how to set function to execute when day has changed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60591487/

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