简体   繁体   English

使用 Onclick 调用嵌套的 function

[英]Using Onclick to call a nested function

I want to implement a basic timer program that starts a 15 second timer on start button and stops on stop button我想实现一个基本的定时器程序,在开始按钮上启动一个 15 秒的定时器并在停止按钮上停止

Here is what I have done so far这是我到目前为止所做的

JS JS

 var timeleft = 15;
 function timer(){
 var downloadTimer = setInterval(function(){
    if(timeleft <= 0){
    clearInterval(downloadTimer);
document.getElementById("countdown").innerHTML = "Finished";
 } else {
   document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
 }
 timeleft -= 1;
  }, 1000);
  function timerstop(){
 clearInterval(downloadTimer);
  }
 }

HTML HTML

<div id="countdown"></div>
<button onclick="timer();">start</button>
<button onclick="timerstop();">stop</button>

The reason I had to use the nested function approach was to access the variable downloadtimer, the start button works as expected but on clicking the stop button I get the following error我必须使用嵌套的 function 方法的原因是访问变量下载计时器,开始按钮按预期工作,但单击停止按钮时出现以下错误

 Uncaught ReferenceError: timerstop is not defined

I would like to know if is this is a programming error or should I change my approach我想知道这是一个编程错误还是我应该改变我的方法

Thanks in Advance提前致谢

Move downloadTimer outside.将 downloadTimer 移到外面。

var timeleft = 15;
var downloadTimer;

function timer() {
    downloadTimer = setInterval(function () {
        if (timeleft <= 0) {
            clearInterval(downloadTimer);
            document.getElementById("countdown").innerHTML = "Finished";
        } else {
            document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
        }
        timeleft -= 1;
    }, 1000);

}

function timerstop() {
    clearInterval(downloadTimer);
}

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

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