Now I have such a problem:
對于webapp 有一個活動列表,列表里每個活動有一個倒計(jì)時,
一旦把a(bǔ)pp切入后臺,js 計(jì)時器就不在生效了,導(dǎo)致倒計(jì)時不準(zhǔn)確,
有想過解決方法,監(jiān)聽visibilitychange事件,觀察document.visibilityState
I want to make a component or function that can solve all the countdown problems on the page,
but my idea is stuck. I wonder if the experts have any good ideas, solutions, or information?
Thanks!
Question supplement:
When I was debugging the timer on my mobile phone, I opened the same page in WeChat and the default browser of the mobile phone,
switched to the background respectively, and found that the page timer in WeChat was still running, and the default browser was The server has stopped running.
When printing in the default browser of the mobile phone, document.visibilityState is undefined, but if the webpage is run in WeChat, it can be printed normally.
Excuse me why? Has WeChat done anything to deal with it?
Compare with the system time of the mobile phone;
If you are still unsure, compare with the system time of the backend when the app is opened.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="app">
<ul>
<li v-for="item in items">
<com1 :value="item.time"></com1>
</li>
</ul>
</p>
<script src="https://cdn.bootcss.com/moment.js/2.17.1/moment.min.js"></script>
<script src="http://cdn.bootcss.com/rxjs/5.2.0/Rx.min.js"></script>
<script src="http://cdn.bootcss.com/vue/2.1.0/vue.min.js"></script>
<script>
const source = Rx.Observable.interval(1000);
Vue.component('com1', {
props: ['value'],
data() {
return {
count: null,
}
},
created() {
source.subscribe(count => this.count = count % 2);
},
template: '<p>距離 {{ value | date("HH:mm:ss") }} 還有 {{ seconds }}s</p>',
computed: {
seconds() {
this.count;
return Math.abs(moment().diff(this.value, 'seconds'));
}
},
filters: {
date(val, format) {
if (val) return moment(val).format(format || 'YYYY-MM-DD HH:mm:ss')
return val
}
}
});
new Vue({
el: '#app',
data() {
return {
items: []
}
},
created() {
for (var i = 0; i < 10; i++) {
this.items.push({
time: moment().add(i + 1, 'hours')
})
}
}
})
</script>
</body>
</html>