Search code examples
javascriptgoogle-chrome-extension

Chrome Extensions: how to set function to execute when day has changed


Currently with my Chrome Extension, I want to execute a block of code whenever a new day begins for a user (users may have different timezones). I was initially looking at this answer but seems pretty dated and was curious about using a Chrome API to help me out.

I was looking into chrome.events and chrome.alarms but found it difficult to read through and find what I wanted.

As of now my code looks like this

background.js

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

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

Solution

  • Using setInterval() or setTimeout() isn't going to work if the user re-starts the browsers or the extension gets restarted for any reason. The same goes for the chrome.alarms API.

    Since it's highly likely for a user to re-start Chrome more than once a day, I would suggest you to save a timestamp in localStorage and then use a setInterval() function that continuously checks if that timestamp has been reached. This way, even if the extension or the whole browser restarts you can still detect that one day has passed.

    Something like this:

    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);