开发者

How to put a JavaScript timer in a box?

开发者 https://www.devze.com 2023-02-05 19:36 出处:网络
I have this JavaScript code: <script type=\"text/javascript\"> function timeMsg() { var t=setTimeout(\"doRedirect()\",10000);

I have this JavaScript code:

<script type="text/javascript">
                function timeMsg() {
                var t=setTimeout("doRedirect()",10000);
                }
                function doRedirect() {
                window.location.replace( "http://www.codemeh.co开发者_运维问答m/" );
                }
                timeMsg();
              </script>

But I want to show how much time is left in a box that floats at the top right, and with my l;ittle knowledge of JavaScript i have no idea where to start :(

Can someone help me?


(function(count) {
   setInterval(function() {
      if( count === 0) {
          window.location.href = "http://www.codemeh.com/";
      }
      else {
          document.getElementById('box_that_floats_top_right').innerHTML = 'Timeleft: ' + (count / 1000);
          count -= 1000;
      }
   }, 1000);
}(10000));

Demo: http://www.jsfiddle.net/4yUqL/77/


A quick solution for you:

<input id="box" type="text" size="8" />

<script>
//Init vars 
var milsec=0;
var sec=30; 
var box = document.getElementById("box");

function display() { 
    if (milsec <= 0){ 
        milsec=9;
        sec-=1;
    } 
    if (sec <= -1){ 
        milsec=0 ;
        sec+=1;
    } else { 
        milsec-=1 ;
        box.value = sec + "." + milsec;
        //call function display after 100ms
        setTimeout(function() {display();},100);
    }
} 
display();
</script>


<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript">

    timeLeft = 10;
    function timeMsg() {
        if(--timeLeft == 0) {
            doRedirect();
        } else {
            $("#time").val(timeLeft);
            setTimeout("timeMsg()",1000);
        }
    }
    function doRedirect() {
        window.location.replace( "http://www.codemeh.com/" );
    }
    $(document).ready(function() {
        $("#time").val(timeLeft);
        setTimeout("timeMsg()",1000);
    });
</script>
<input id="time" size="5"></input>
0

精彩评论

暂无评论...
验证码 换一张
取 消