即使我没有按下按钮,JS代码也始终运行

时间:2018-09-20 11:29:57

标签: javascript

我有一个js代码,当我单击按钮时我想运行它。对我来说似乎可以,但是即使我没有按下按钮也可以运行它。

也许它有一个简单的答案,但我无法处理。我是新来的...。

var upgradeTime = 600;
var seconds = upgradeTime;

function timer() {
    var days        = Math.floor(seconds/24/60/60);
    var hoursLeft   = Math.floor((seconds) - (days*86400));
    var hours       = Math.floor(hoursLeft/3600);
    var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
    var minutes     = Math.floor(minutesLeft/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds; 
    }
    document.getElementById('countdown').innerHTML = 
        days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Tamamlandı.";
    } else {
        seconds--;
    }
}

var countdownTimer = setInterval('timer()', 1000);
<span id="countdown" class="timer"></span>

<input id="" type="button" value="clickme" onclick="timer();" />

2 个答案:

答案 0 :(得分:1)

您需要删除函数外的var countdownTimer = setInterval('timer()', 1000);

  1. 您可以将所有核心逻辑包含在新功能coreTimer()
  2. coreTimer()致电timer()
  3. 确保countdownTimer在全局范围内声明,以便可以在clearInterval函数内使用coreTimer()清除它。

var upgradeTime = 10;
var seconds = upgradeTime;
var countdownTimer;
function timer() {
   countdownTimer = setInterval('coreTimer()', 1000);
}

function coreTimer() {
  var days = Math.floor(seconds / 24 / 60 / 60);
  var hoursLeft = Math.floor((seconds) - (days * 86400));
  var hours = Math.floor(hoursLeft / 3600);
  var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
  var minutes = Math.floor(minutesLeft / 60);
  var remainingSeconds = seconds % 60;
  if (remainingSeconds < 10) {
    remainingSeconds = "0" + remainingSeconds;
  }
  document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
  if (seconds == 0) {
    clearInterval(countdownTimer);
    document.getElementById('countdown').innerHTML = "Tamamlandı.";
  } else {
    seconds--;
  }
}
<span id="countdown" class="timer"></span>

<input id="" type="button" value="clickme" onclick="timer();" />

答案 1 :(得分:1)

setInterval方法以指定的时间间隔调用函数或计算表达式。因此,声明

var countdownTimer = setInterval('timer()', 1000);

将每1000毫秒执行一次计时器功能。因此,即使不单击按钮,也会调用您的函数。您需要相应地修改该语句或将其完全删除。