![](/img/trans.png)
[英]How to make a setInterval stop after some time or after a number of actions?
[英]how to make a setInterval stop after some time
我有一个加载 function 显示文本,延迟为 6 秒,持续 4 秒,然后它应该停止并且应该执行 function
function loading() {
let abc = ['A', 'B', 'C', 'D', 'E', 'F'];
let i = 0;
return new Promise((resolve, reject) => {
setTimeout(() => {
setInterval(() => {
i = (i > 5) ? 0 : i;
//console.clear();
console.log(abc[i]);
i++;
const error = false;
if (!error) {
resolve();
} else {
reject('Error: smth went wrong')
}
}, 300);
}, 6000)
})
};
function loadingStop() {
setTimeout(() => {
console.log('some text');
}, 4000);
}
loading().then(loadingStop);
但是 loadingStop function 没有停止加载
例如,可以使用clearInterval(timerId)
。
function loading() { let abc = ["A", "B", "C", "D", "E", "F"]; let i = 0; return new Promise((resolve, reject) => { const timerId = setInterval(() => { i = i > 5? 0: i; console.log(abc[i]); i++; }, 300); setTimeout(() => { clearInterval(timerId); reject("Error: smth went wrong"); }, 6000); }); } function loadingStop() { console.log("some text"); } loading().then(loadingStop).catch(console.error);
您必须先将间隔保存到变量中
const interval = setInterval(() => console.log('Hi'), 3000);
然后使用clearInterval清除/结束它
clearInterval(interval);
你能在变量中定义setInterval吗,当你想停止setInterval时,你调用function clearInterval(varname),clearInterval是js的原生function停止setInterval,希望对你有所帮助。
var intervalx = setInterval(function(
console.log('hello')
}, 1000);
clearInterval(intervalx);
不太确定我完全理解这里需要什么,但可能......
如果是这样,那么问题中的大部分代码都很好。 它只是缺少一种机制来强制 animation 在超时发生之前停止。
这可以通过将令牌(一个 JS 普通对象)传递给loaing()
来实现。
function loading(token) {
return new Promise((resolve, reject) => {
// Basic animation data
let abc = ["A", "B", "C", "D", "E", "F"];
let i = 0;
// Establish a stoppable animation
let timerId = setInterval(() => {
if(token.stop) { // has stop command been issued?
clearInterval(timerId); // kill the animation
resolve('stopped');
} else {
console.log(abc[i]); // the "animation"
i = (i+1) % 5;
}
}, 300);
// Stop the animation after a certain timeout period
setTimeout(() => {
clearInterval(timerId); // kill the animation
reject(new Error("time out")); // always reject with an Error
}, 6000);
});
}
// Token (allows a "stop" command to be issued)
let token = {};
// Simulated "stop" event
setTimeout(() => {
token.stop = true;
}, 4000);
// Call loading() and log normal/error completion.
loading(token).then(console.log).catch(console.error);
如前所述,在 4 秒后发出停止命令,将记录“已停止”。
通过将4000
更改为8000
,将在停止命令之前发生超时,并且将记录“错误:'超时'”。
在实践中,您可能希望通过将6000
甚至300
作为参数传递给loading()
来为自己提供一定的灵活性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.