JS計時器


這個代碼我折騰了好久,發現以下幾點不足:

1、對onclick三種調用方式不熟悉,一是無參數調用,二是有參數調用,三是this 調用

2.存在只是盲點,不知道clearInterval()

3、對js函數理解不夠透徹。

<body>
    alarm clock: <span id = "alarmID"></span><br>
    <input  type="button" value="start"  onclick="start()">
    <input type="button" value="stop"  onclick="stop()">
  
    <script type="text/javascript"> 
         var alarm_obj = document.getElementById("alarmID");
         var timer_id;
         function time(){
                var time_now = new Date();
                 time_now = time_now.toLocaleString();
                alarm_obj.innerHTML = time_now;  //把time_now的字符串寫入alarmID指向的標簽內容中
            }
        function start(){  
           timer_id = window.setInterval("time()", 1000); //time_id是一個固定的整數
        }
        function stop(){
           window.clearInterval(timer_id);
        }
     </script>
</body>

下面是錯誤寫法

 

<body>
    alarm clock: <span id = "alarmID"></span><br>
    <input  type="button" value="start"  onclick="start()">
    <input type="button" value="stop"  onclick="stop()">
  
    <script type="text/javascript"> 
         var alarm_obj = document.getElementById("alarmID");
         var timer_id;
        
        function start(){
            var time_now = new Date();
            time_now = time_now.toLocaleString();
            alarm_obj.innerHTML = time_now; 
            timer_id = window.setInterval("start()", 1000); //無線循環自我調用,使得stop函數無法運行
        }
        function stop(){
           window.clearInterval(timer_id);
        }
     </script>
</body>

 下面是簡單的登錄界面

login.html

<body>
   <form action="#" name="loginForm" method="get">
       username: <input type="text" name="userName" value="luoxu">
       password: <input type="password" name="password" value="123">
      <input type="button" value="login" onclick="checkUser()">
   </form>
    <script type="text/javascript"> 
        var userName = loginForm.userName.value;
        var password = loginForm.password.value;
        function checkUser(){
            if(userName == "luoxu" && password == "123"){
                window.open("loginOk.html", "_self");
            }else{
                window.alert("Input error");
            }
        }
     </script>
</body>

 

5秒后跳轉頁面

loginOk.html

<body>
    Return after <span id = "timer">5</span>seconds! <br>
    <script type="text/javascript"> 
        var time_span = window.document.getElementById("timer"); //js代碼必須在span后面,否則取不到span對象
        var time_id = window.setInterval("timer()", 1000);
        function timer(){
           var time_count = time_span.innerHTML - 1;
            time_span.innerHTML =time_count;
            if(time_count == 0){
                window.clearInterval(time_id);
                window.open("test.html", "_self");
            }
        }
     </script>
</body>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM