Search code examples
alpine.js

How to make timer in alpine.js app with time interval


With alpine.js 2 I try to make timer with definition in footer (which is set for all layout) of the app :

<div>    
    <div x-data="appFooterComponent()" x-init=" console.log('initTimer()::'); refreshTime();
        setInterval(refreshTime, 1000) ; console.log('END initTimer::');">
        <div >
            ...
            <span style="background-color: yellow" x-text="refreshTime(@this)"></span>
        </div>
    </div>
</div>

<script>
    // THAT DOES NOT WORK
    // this.refreshTime()
    // setInterval(refreshTime, 1000)
    function appFooterComponent() {
        return {
            refreshTime() {
                return moment(new Date()).format('DD MMMM, YYYY HH:mm:ss')
            },
        }
    }
</script>

As result when any new page is opened I see how current datetime is set, but without interval and time is not refreshed any second. In console I see output of x-init console commands, but not time interval... How to fix it ?

Thanks!


Solution

  • Would the following work?

    What you probably want to do with Alpine.js is have a time variable that you update (using setInterval), then you can read the formatted time using this.time and the relevant Moment.js expression.

    <div>
        <div x-data="appFooterComponent()" x-init="init()">
            <div>
                ...
                <span style="background-color: yellow" x-text="getTime()"></span>
            </div>
        </div>
    </div>
    
    <script>
        function appFooterComponent() {
            return {
                time: new Date(),
                init() {
                  setInterval(() => {
                    this.time = new Date();
                  }, 1000);
                },
                getTime() {
                    return moment(this.time).format('DD MMMM, YYYY HH:mm:ss')
                },
            }
        } 
    
    </script>