微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Onclick 调用嵌套函数

如何解决使用 Onclick 调用嵌套函数

我想实现一个基本的计时器程序,在开始按钮上启动一个 15 秒的计时器并在停止按钮上停止

这是我目前所做的

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

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

我必须使用嵌套函数方法的原因是访问变量下载计时器,开始按钮按预期工作,但单击停止按钮时出现以下错误

 Uncaught ReferenceError: timerstop is not defined

我想知道这是编程错误还是我应该改变我的方法

提前致谢

解决方法

将 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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。