【发布时间】:2021-11-29 15:24:05
【问题描述】:
这是设置。我希望在 5 秒后停止 looper (setInterval()) 的运行。
我有很多cmets,所以应该很容易理解,有什么问题可以问我。
我尝试移动 if 语句(检查计时器值 === 5000)。在 setInterval 函数里面试过,在 onClick 函数里面试过。
我也尝试过运行以 window 为前缀的 setInterval() 和 clearInterval()。
大家有什么想法吗? ?????? ????
window.onload = function(){
var looper;
var degrees = 0;
var timer = 0; // timer used to monitor how long the wheel has been spinning
function startWheelAnimation(elementId, speed){
// 1. get the element to rotate
const ele = document.getElementById(elementId); // get the HTML element to rotate
const cssRotateVal = "rotate("+degrees+"deg)"; // the CSS style rotate value
// 2. CSS3 browser compatibility checks
if(navigator.userAgent.match("Chrome")){
ele.style.WebkitTransform = cssRotateVal;
} else if(navigator.userAgent.match("Firefox")){
ele.style.MozTransform = cssRotateVal;
} else if(navigator.userAgent.match("MSIE")){
ele.style.msTransform = cssRotateVal;
} else if(navigator.userAgent.match("Opera")){
ele.style.OTransform = cssRotateVal;
} else {
ele.style.transform = cssRotateVal;
}
// 3. start looping at the rate of speed var
looper = setInterval( ()=>{
// at the rate of speed var run the following code
startWheelAnimation( elementId, speed );
},
speed);
degrees++; // increment the degrees value by 1
timer++; // increment the timer value by 1
console.log(timer); // devtool
if( degrees > 359 ){ // reset the degrees value back to 0 upon a full rotation
degrees = 0;
clearInterval(looper); // stop the wheel spinning
}
if( timer === 5000 ){ // after 5 seconds has passed reset the timer and stop the looper
console.log(looper);
timer = 0;
clearInterval(looper); // stop the wheel spinning
}
}
document.getElementById('spinButton').addEventListener("click", event => {
const speed = 100;
startWheelAnimation("wheel", speed);
});
}
【问题讨论】:
-
对 vanilla JS 中的动画内容不太了解,但我在这里看到了一个递归函数,我看不到如何通过 clearinteval() 调用终止堆栈中的所有函数调用??????
-
除了所有 cmets 和答案,您还必须查看
requestAnimationFrame而不是setInterval -
接受的答案有解决方案! :)
标签: javascript settimeout setinterval clearinterval cleartimeout