繁体   English   中英

函数不能被多次调用

[英]Function cannot be called more than once

StopBtn不能被调用两次

一旦函数被调用,它将保持不变并且不起作用,并且我还收到一条错误消息,说Timer不是对象。 我真的不知道是什么问题

var timer = setInterval(clock, 1000);

function clock() {
  var date = new Date();
  var time = date.toLocaleTimeString();

  document.getElementById("time").innerHTML = "The Current time is > " + time;
}

var startBtn = document.getElementById("start");
var stopBtn = document.getElementById("stop");

stopBtn.addEventListener("click", stopTime);

function stopTime() {
  var stoptime = clearInterval(timer);
  console.log("Stop");
}

startBtn.addEventListener("click", startTime);

function startTime() {
  var starttime = setInterval(clock, 1000);
  console.log("hello");
}
<html>

<head>
  <link rel="stylesheet" href="style.css" />
  <link href="https://fonts.googleapis.com/css?family=Baloo+Bhai&display=swap" rel="stylesheet" />
</head>

<body>
  <button id="stop">STOP TIME</button>
  <button id="start">START TIME</button>
  <h1 id="h1">We are Coding JavaScript</h1>
  <h3>Keep On Practicing Dude!</h3>

  <div id="time"></div>

  <script src="script.js"></script>
</body>

</html>

startTime函数中,您正在设置一个新变量以与计时器关联。 stopTime函数不使用该变量,因此在按下“开始”按钮后它不会停止计时器。

只需在计时器的整个代码中重用一个变量即可。

笔记:

实际上,您有比所需的更复杂的解决方案。 因为它们都需要做相同的事情,所以不需要启动时钟的clock()函数和调用clock函数的startTime函数。

代替使用setInterval() ,而使用setTimeout (这是一个一次性计时器),但是将计时器放置在start函数中,使其变得递归。

当您要获取/设置的字符串不包含任何HTML时,请勿使用.innerHTML,因为.innerHTML具有安全性和性能方面的意义。 使用DOM元素字符串时,请使用.textContent

仅扫描DOM一次即可发现您要反复使用的元素。

 var startBtn = document.getElementById("start"); var stopBtn = document.getElementById("stop"); var clock = document.getElementById("currentTime"); startBtn.addEventListener("click", startClock); stopBtn.addEventListener("click", stopClock); // This one variable will represent the timer // throughout the code var timer = null; function startClock() { var now = new Date(); var time = now.toLocaleTimeString(); clock.textContent = "The Current time is > " + time; timer = setTimeout(startClock, 1000) } function stopClock() { clearTimeout(timer); console.log("Stop"); } startClock(); 
 <button id="stop">STOP TIME</button> <button id="start">START TIME</button> <div id="currentTime"></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM