vue.js

Destroy the timer in beforeDestroy (preferably with the $once event listener)





I have written a timer in page A, such as printing 1 every second. When I click the button to enter page B, I will find that the timer is still running, which is very performance consuming. ② Solution 1:

Option 1: There are two downsides, to quote Yoo: it needs to save the timer in the component instance, preferably only the lifecycle hooks can access it if possible. This is not a serious problem, but it can be considered clutter. Our build code is separate from our cleanup code, which makes it harder to programmatically clean everything we build.

    
    mounted() {
        this.timer = setInterval((a)= > {
             console.log(1)},1000)
    },
    beforeDestroy() {
        clearInterval(this.timer)
    }
    
Copy the code


Option 2 (recommended) : This method clears the timer by the position of the $once event listener after the timer is defined


    mounted() {
        const timer = setInterval((a)= > {
            console.log(1)},1000)
        this.$once('hook:beforeDestroy', () => {
            clearInterval(timer)
        })
    }

Copy the code



    mounted(){
        let picker = new Pikaday({
            field: this.$refs.input,
            format: 'YYYY-MM-DD'
        })

        this.$once('hook:beforeDestory', ()=>{
            picker.destory()
        })
    }

Copy the code