为什么setInterval会产生无限循环 [英] Why is setInterval making infinite loops

查看:185
本文介绍了为什么setInterval会产生无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个计时器,以便显示用户的秒数和最小值,我使用setInterval来获取秒数,如果有60秒,它将减少用户1分钟。
事情就是我每次尝试都会得到无限的foorloops。

I'm trying to set a timer so it display the seconds and min left of an user and I'm using setInterval to get the seconds and if there are 60 seconds it will reduce 1 min from the user. The thing is that I'm getting infinite foorloops every time i try to do it.

类似

var userObj = {
    name: "",
    min: 0,
    sec:0
}

function timerCount() {
    while (userObj.sec !== 0) {
        console.log(userObj.min)
        if (userObj.sec == 0) {
            setInterval(function() {
                userObj.min--;
                userObj.sec = 59     
            }, 1000);
        }
        while(userObj.sec !== 0) {
            setInterval(function() {
                console.log(userObj.sec)
                userObj.sec--;  
            }, 1000);
        }
    }
}


推荐答案

var userObj = {
    name: "",
    min: 0,
    sec:5
}

function timerCount() {

  if(userObj.min === 0 && userObj.sec === 0) {
    return;
  }

  if (userObj.sec === 0) {
    userObj.min--;
      userObj.sec = 59     
    }     
  userObj.sec--;  


  setTimeout(timerCount, 1000)
}

timerCount()

我们可以毫不费力地删除导致问题的循环。我们还想检查等于0的分钟和秒数,以便我们知道何时结束我们的计时器。

With little effort we can remove those while loops that are causing the issue. We also want to check for the minutes and seconds equalling 0 so we know when to end our timer.

这篇关于为什么setInterval会产生无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆