Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: Detecting new day (day changed) in Javascript?

I know there's not a event listener for a new day (or hour/minute, for that matter). But in my Chrome Extension, I need to know when a new day has started, and which means I'll have to use a setInterval function to find out when the day has changed. However, I'm not sure what to use for the interval value: 10 seconds, or 10 minutes? I'm worried about using up CPU & memory (constant setInterval calls), but I still want to know almost as soon as a new day starts. Any ideas as to what is the ideal way to handle this?

like image 975
mattsven Avatar asked Dec 07 '25 04:12

mattsven


1 Answers

If you mean a new day for the user, you can set a single timeout when the page loads.

function setnewdaytimer(){
    if(window.newdaytimer) clearTimeout(newdaytimer);
    var now= new Date,
    tomorrow= new Date(now.getFullYear(), now.getMonth(), now.getDate()+1); 
    window.newdaytimer= setTimeout(newdayalarm, tomorrow-now);
}
function newdayalarm(){
    alert((new Date()).toLocaleTimeString());
}

window.onload=setnewdaytimer;
like image 89
kennebec Avatar answered Dec 08 '25 16:12

kennebec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!