我的函数有问题,页面更改后,函数继续运行并且出现错误,我该如何停止它,谢谢
componentDidMount() {
var current = 0;
var slides = document.getElementsByClassName("j1");
setInterval(function() {
let rec = window.location.href;
rec = rec.split('/');
console.log(rec);
for (var i = 0; i < slides.length; i++) {
slides[i].style.opacity = 0;
for (var j = 0; j < 10000; j++) {
let k = j;
}
}
current = (current != slides.length - 1) ? current + 1 : 0;
slides[current].style.opacity = 1;
}, 5000);
}
最佳答案
您必须注销时间间隔。像这样:
class Example extends React.Component {
componentDidMount() {
this.timer = window.setInterval(function() {
....
}, 5000);
}
componentWillUnmount() {
window.clearInterval(this.timer);
}
}
关于javascript - setInterval在页面更改后正在运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52935855/