简体   繁体   English

标签重新获得焦点后SetInterval赶上来

[英]SetInterval catching up after tab regains focus

I have a setinterval function that changes a variable in Vue's data. 我有一个setinterval函数,用于更改Vue数据中的变量。

When the tab loses focus and then regains it back the SetInterval tries to catch up and goes crazy. 当选项卡失去焦点然后重新找回时,SetInterval会尝试追赶并发疯。

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 ... 在什么情况下程序员希望函数每5秒运行一次,但是如果它每0.3秒运行10次也可以。

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: 您可以使用诸如document.hasFocus()之类的选项来检查选项卡是否处于活动状态:

 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. 注意:使用上面的代码段,您必须在结果内单击以使示例聚焦,因为该示例位于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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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