javascript - 单击另一个页面上的按钮后如何启动计时器?
问题描述
我有几个问题想放在一起。
- 单击另一个页面上的按钮后,如何启动倒数计时器?
- 单击计时器后,如何防止在页面刷新时重置?(我找到了使用 cookie 等的示例,但我找不到将它们添加到下面代码中的方法)。
- 计时器只会在按下按钮时停止。
import React, { Component } from 'react'
class Timer extends Component {
state = {
minutes: 1,
seconds: 0,
}
componentDidMount() {
this.myInterval = setInterval(() => {
const { seconds, minutes } = this.state
if (seconds > 0) {
this.setState(({ seconds }) => ({
seconds: seconds - 1
}))
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(this.myInterval)
} else {
this.setState(({ minutes }) => ({
minutes: minutes - 1,
seconds: 59
}))
}
}
}, 1000)
}
componentWillUnmount() {
clearInterval(this.myInterval)
}
render() {
const { minutes, seconds } = this.state
return (
<div>
{ minutes === 0 && seconds === 0
? <h1></h1>
: <h1>Timer is counting: {minutes}:{seconds < 10 ? `0${seconds}` : seconds}</h1>
}
</div>
)
}
}
export default Timer
任何帮助将不胜感激。先感谢您 :)
解决方案
- 定义倒计时时间
const TIMER_TIME = 120; // time of the timer in seconds
- 通过保存定时器启动时间来启动超时
localStorage.setItem('timer-start', new Date().getTime()); // can be called from any page, trigger by any thing
- 处理组件中的剩余时间
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = this.calculateTimer();
}
calculateTimer = () => {
const startTime = localStorage.getItem('timer-start'); // get data of time start
if(!startTime) return {seconds:0,minutes:0};
const timeLeft = TIMER_TIME - (new Date().getTime() - startTime) / 1000; // timeleft = timer time -time over
if(timeLeft <= 0) { // reset timer if its finish
localStorage.removeItem('timer-start');
clearTimeout(this.myInterval);
return {seconds:0,minutes:0}
}
return {minutes: Math.floor(timeLeft/60), seconds: Math.floor(timeLeft%60)}
}
componentDidMount() {
this.myInterval = setInterval(() => this.setState(this.calculateTimer()), 1000)
}
componentWillUnmount() {
clearInterval(this.myInterval)
}
render() {
const { minutes, seconds } = this.state
return (
<div>
{ minutes === 0 && seconds === 0
? <h1></h1>
: <h1>Timer is counting: {minutes}:{seconds < 10 ? `0${seconds}` : seconds}</h1>
}
</div>
)
}
}
推荐阅读
- python - 当 a=10 时,python 内部实际发生了什么,
- reactjs - 如何在 reactjs 项目的引导程序 5 中停止在轮播中的最后一个滑块图像上滑动
- php - PHP函数在应该返回多行时只返回一行
- vba - VBA word - 为表格设置字体样式
- node.js - 在再次刷新后保存mongoDB数据时保存相同的数据
- amazon-web-services - 如何将 www 重定向到 AWS 上的非 www 静态网站
- angular - 拖放列表内的项目以及对内部项目进行排序
- node.js - 如何在 pm2 中按日期分隔日志?
- javascript - 如何在 val: 'this text' ionic 5 Angular 中添加换行符?
- reactjs - 为什么样式不会从状态改变?