这是我的代码
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!
以下代码每250ms运行一次任务,并在5秒后停止。我希望这会给你一些灵感。
var intervalId = setInterval(() => console.log("running"), 250);
setTimeout(() => clearInterval(intervalId), 5000);
所以它有效)
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);
这是你的错误:不要小心使用this
:你应该花时间去理解how this
works in 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);