【问题标题】:call function inside setInterval [duplicate]setInterval 内的调用函数 [重复]
【发布时间】:2019-10-10 05:48:32
【问题描述】:

我想在定时器值变为0时调用一个函数。当我点击卡片时,会打开一个弹出窗口,然后定时器启动。下面是代码:

openModal() {
  switch (area) {
    case 'a':
      var self_t = this;
      uid = 11;
      let timer = 20;
      let interval = setInterval(function () {
          let elementID = document.getElementById('float-div');
          if(elementID == null) {
            timer = this.inSeconds;
          }
          if(timer >= 0) {
            if(elementID) {
              elementID.innerHTML = String(timer);
            }
          }
          if (--timer == 0) {
              if(elementID) {
                  elementID.innerHTML = '0';
              }
              if(area == "a") {
                 self_t.callFunction(uid); // here it is not going, I put debugger here but i can see it doesn't go here!                          
                 clearInterval(interval);
              }
          }
    }, 1000);
    break;

    case 'b':
    console.log('something else');
    break;
  }
}

callFunction(uid) {
  console.log(uid);
}

已经试过了:using var self=this

如果我使用this.callFunction(uid),则会引发错误。

【问题讨论】:

  • 使用箭头函数给你写信 setInterval 就可以了。
  • 它抛出的错误是什么
  • @Manish 我没明白,如何在我的代码中使用,因为我有某些条件要检查,当 timer == 0 时调用该函数。
  • @PathikVejani 发布了答案看看。

标签: javascript angular typescript


【解决方案1】:

为此使用箭头功能。下面是一个 sn-p 试试这个它会做的伎俩。 Read more about Arrow functions

openModal() {
  switch (area) {
    case 'a':
      uid = 11;
      let timer = 20;
      let interval = setInterval(() => {
        let elementID = document.getElementById('float-div');
        if (elementID == null) {
          timer = this.inSeconds;
        }
        if (timer >= 0) {
          if (elementID) {
            elementID.innerHTML = String(timer);
          }
        }
        if (--timer == 0) {
          if (elementID) {
            elementID.innerHTML = '0';
          }
          if (area == "abc") {
            this.callFunction(uid); // here it is not going, I put debugger here but i can see it doesn't go here!                          
            clearInterval(interval);
          }
        }
      }, 1000);
      break;

    case 'b':
      console.log('something else');
      break;
  }
}

callFunction(uid) {
  console.log(uid);
}

更新:

使用箭头函数时不需要下面的语句。 this 将在函数内部可用。

  var self_t = this;

希望这会有所帮助:)

【讨论】:

  • 成功了!谢谢!
  • 不客气。很高兴能帮上忙:)
【解决方案2】:

也许你应该修改这些代码

 if(elementID == null) {
            timer = this.inSeconds;
          }

 if(elementID == null) {
            timer = self_t.inSeconds;
          }

【讨论】:

  • 我正在获取计时器值,问题只是无法调用该函数!
  • 我发现了一些笑话代码....;当您在case 'a' 块中使用它时,if (area == "abc") { 永远不会是真的;我不确定,是不是这个问题?
  • 这只是测试代码!
猜你喜欢
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 2019-02-25
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多