Search code examples
javascriptgoogle-chrome-extensionweb-applications

How to reset a variable to 0 every 24 hours in Javascript?


I want to reset a variable automatically without any user interaction to 0 every midnight.

How to do that in vanilla Javascript?

Or does Chrome have any default method to do it. Because I store that variable in Chrome.storage.local.

What is the best way to do it in either vanilla JS or using chrome apis?


Solution

  • It is impossible to do so automatically without user accessing the page.

    But, you can add script to the page which onload check the last time the value was stored and if the time passed you can reset the variable.

    Rough code to make this:

    const isToday = (someDate) => {
      const today = new Date()
      return someDate.getDate() == today.getDate() &&
        someDate.getMonth() == today.getMonth() &&
        someDate.getFullYear() == today.getFullYear()
    }
    
    window.onload = function init() {
        const { value, date } = JSON.parse(localStorage.getValue('key'));
        
        if (!isToday(date)) {
            localStorage.setValue('key', JSON.stringify({ date: new Date(), value: defaultValue}))
        }
    }