【问题标题】:how to stop function in 5 seconds? Vue.js如何在 5 秒内停止功能? Vue.js
【发布时间】:2019-04-04 11:25:26
【问题描述】:

这是我的代码

 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!

【问题讨论】:

  • 您检查控制台是否有任何错误消息?
  • intervalAddImage 不是函数
  • 你能展示你的整个代码吗? this 来自哪里,你是从对象运行它,还是使用隐式全局/窗口对象?
  • @jcubic setTimeout(setInterval(this.addImage, 250), 5000); ??在这种情况下,功能不会停止
  • 删除的评论是错误的。检查我的其他评论。

标签: javascript arrays vue.js


【解决方案1】:

以下代码每 250 毫秒运行一次任务,并在 5 秒后停止。我希望这能给你一些启发。

var intervalId = setInterval(() => console.log("running"), 250);
setTimeout(() => clearInterval(intervalId), 5000);

【讨论】:

    【解决方案2】:

    这样就可以了)

    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);
    

    【讨论】:

    • "intervalAddImage 不是函数"
    • @GermanVaranytsya 只需删除对intervalAddImage(); 的调用,因为那不是函数而是数字。
    【解决方案3】:

    这是你的错误:不要在不小心的情况下使用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);

    【讨论】:

    • 我需要addImage
    • 如果您需要致电addImage,我已经更新了sn-p。您会发现取消注释以启用它的行。另一种方法是将bind 函数设置为this 值,这样this 就是你希望它在函数中的值。
    • 但是请花点时间阅读 this 在 JavaScript 中的工作原理,否则你会遇到很多问题。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    猜你喜欢
    • 2019-05-16
    • 2020-10-20
    • 2020-01-09
    • 2018-01-28
    • 1970-01-01
    • 2019-10-17
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多