问答详情
源自:3-4 编程练习

为什么上节讲的时候可以timer = setInterval(autoPlay(), 2000);这样写,而我这样写就只能执行一次,就是1秒后没不执行了

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        window.onload=function(){
            var send=document.getElementById('send'),
            second=document.getElementById('second'),
                    times=5,
                    timer=null;
            send.onclick = function () {
                // 计时开始
 timer = setInterval(function () {
                    autoPlay();
                }, 1000)
            }
            //自动播放
 function autoPlay(){
                if (times <= 0){
                    times = 5;
                    send.disabled=false;
                    send.value = '发送验证码';
                    second.innerHTML=0;
                    clearInterval(timer)
                    return;
                }
                send.disabled=true;
                send.value = '正在发送...';
                second.innerHTML=times;
                times--;
            }
        }
    </script>
</head>
<body>
<input type="button" id="send" value="发送验证码"><button disabled><span id="second">0</span>秒后重试</button>
</body>
</html>

为什么现在只能写在function内了

提问者:qq_文兵 2016-01-06 11:56

个回答

  • 李晓健
    2016-01-06 12:11:56

    timer = setInterval(autoPlay, 1000);   //直接这么写的话autoPlay后面不能加()