Javascript 在React中停止来自另一个函数的间隔
我是一个新的反应,我试图建立一个计时器组件。现在我有了start函数,但我还想通过onclick处理程序停止计时器。问题是start函数使用了一个间隔,但我不知道如何从另一个函数停止该间隔 我的JS代码Javascript 在React中停止来自另一个函数的间隔,javascript,reactjs,Javascript,Reactjs,我是一个新的反应,我试图建立一个计时器组件。现在我有了start函数,但我还想通过onclick处理程序停止计时器。问题是start函数使用了一个间隔,但我不知道如何从另一个函数停止该间隔 我的JS代码 constructor() { super(); this.state = { times: [], timer: false, currentTimer: 0 } this.startTimer = this.star
constructor() {
super();
this.state = {
times: [],
timer: false,
currentTimer: 0
}
this.startTimer = this.startTimer.bind(this);
this.stopTimer = this.stopTimer.bind(this);
}
startTimer() {
const start = Date.now();
this.setState({ timer: true });
var timer = setInterval(() => {
let time = new Date() - start;
this.setState({ currentTimer: Math.round(time / 1000)});
}, 1000);
}
stopTimer() {
this.setState({ timer: false });
console.log('stopped');
//Clear interval here
}
我知道
timer
变量是该间隔的标识符,但如何访问它并停止它?我已经尝试了几乎所有的方法,但似乎没有任何效果,我只是不知道如何解决这个问题。要停止计时器,您需要计时器id,因此第一项工作是以所有类方法都可以访问的方式存储id。
第二个作业将使用clearInterval
清除计时器(此处需要计时器id)
一个选项是,将计时器id存储在类实例中
像这样:
startTimer() {
const start = Date.now();
this.setState({ timer: true });
// storing the id
this.timerID = setInterval(() => {
let time = new Date() - start;
this.setState({ currentTimer: Math.round(time / 1000)});
}, 1000);
}
stopTimer() {
this.setState({ timer: false });
clearInterval(this.timerID);
}
工作代码:
类应用程序扩展了React.Component{
构造函数(){
超级();
this.state={currentTimer:'}
this.startTimer=this.startTimer.bind(this);
this.stopTimer=this.stopTimer.bind(this);
}
startTimer(){
const start=Date.now();
this.timerID=setInterval(()=>{
让时间=Math.random()*10;
this.setState({currentTimer:time});
}, 1000);
}
停止计时器(){
clearInterval(this.timerID);
}
render(){
返回(
值:{this.state.currentTimer | |'0'}
启动计时器
停止计时器
)
}
}
ReactDOM.render(,document.getElementById('app'))
将timerId另存为类实例变量,然后可从其他函数访问该变量并用于清除间隔
constructor() {
super();
this.state = {
times: [],
timer: false,
currentTimer: 0
}
this.timer = null;
this.startTimer = this.startTimer.bind(this);
this.stopTimer = this.stopTimer.bind(this);
}
startTimer() {
const start = Date.now();
this.setState({ timer: true });
this.timer = setInterval(() => {
let time = new Date() - start;
this.setState({ currentTimer: Math.round(time / 1000)});
}, 1000);
}
stopTimer() {
this.setState({ timer: false });
console.log('stopped');
//Clear interval here
clearInterval(this.timer)
}
您的
timer
变量是startTimer()
方法的局部变量,它存储该间隔的标识符,但在函数范围之外无法访问
要解决此问题,请在constructor()
方法中添加以下内容:
this.timer = null;
//Clear interval here code here
clearInterval(this.timer);
然后,在startTimer()
方法更改中:
var timer = setInterval(() => {
let time = new Date() - start;
this.setState({ currentTimer: Math.round(time / 1000)});
}, 1000);
致:
最后,在stopTimer()方法中添加以下内容:
this.timer = null;
//Clear interval here code here
clearInterval(this.timer);