[英]how to stop function in 5 seconds? Vue.js
这是我的代码
setInterval(this.randomImage, 250);
setInterval(this.randomPosition, 250);
setInterval(this.addImage, 250);
我想在5秒钟内停止addImage功能,因为图像无限增加!
我试图通过这种方式做到这一点
let timesRun = 0;
const intervalAddImage = setInterval(function () {
timesRun += 1;
if (timesRun === 60) {
clearInterval(intervalAddImage)
}
this.addImage();
}, 250);
intervalAddImage();
但这行不通...
我正在使用Vue.js!
以下代码每250毫秒运行一次任务,并在5秒后停止。 我希望这会给您一些启发。
var intervalId = setInterval(() => console.log("running"), 250); setTimeout(() => clearInterval(intervalId), 5000);
这是您的错误:请勿不加小心地使用this
:您应该花一些时间来了解this
在JavaScript中的工作方式 。
在您的代码中,您增加了this.timesRun
,但是您对timesRun
进行了测试,但从未增加。
该示例将按您期望的方式工作:
let timesRun = 0; //const addImage = this.addImage; const intervalAddImage = setInterval(function () { timesRun += 1; if (timesRun === 60) { clearInterval(intervalAddImage); } //addImage(); console.log("Hello", timesRun); }, 250);
这样就可以了)
let timesRun = 0; // just change to this
function addImage(timesRun) { console.log(timesRun)}
const intervalAddImage = setInterval(function () {
timesRun += 1; // just change to this
if (timesRun === 4) {
clearInterval(intervalAddImage)
return; // add this
}
addImage(timesRun);
}, 250);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.