简体   繁体   中英

SetInterval catching up after tab regains focus

I have a setinterval function that changes a variable in Vue's data.

When the tab loses focus and then regains it back the SetInterval tries to catch up and goes crazy.

I see the logic behind slowing it or stopping it completely to preserve resources or battery, but catching up is something I see no use of. What's a case in which a programmer would want a function to run every 5 seconds, but it will be fine if it runs 10 times every 0.3 seconds as well ...

Anyway, is there better solution or something I should add?

created() {
    setInterval(() => this.moveSlider(), 7000);
},

You can use something like document.hasFocus() to check if the tab is active or not:

 new Vue({ el: '#app', template: '#base', data () { return { count: 0 } }, created () { setInterval(() => { this.incrCount(); }, 2000); }, methods: { incrCount() { if (document.hasFocus()) this.count++; else console.log("Not in focus"); } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <template id="base" v-cloak> <div> <h3>Click here to see the count go up</h3> <div>{{count}}</div> </div> </template> <div id="app"></div> 

Note: with the snippet above, you have to click inside the result for the example to go into focus because it is in an iframe. Click anywhere outside of the example to see it stop, then back in to resume the action without it trying to catch up.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM