Agha Hasan
Agha Hasan

Reputation: 49

how can I stop the seconds on 60 to 0

Hi im new to javascript and html , I just want to know that how can I stop the third text field(txtS) at 60 to 0. I'm trying to make a clock ,so the seconds need to stop at 60 and minutes should start incrementing.**

I'm only asking is to how to stop seconds at 60

<html >
<head>
    <title>clock</title>
    <script language="javascript">
        function fn_sample() {
            document.frm.txtS.value = parseInt(document.frm.txtS.value) + 1;
            var t1 = document.frm.txtS.value;
            if(t1>=60){

                t1 = 0;

            }
            window.setTimeout("fn_sample()", 1000);

        }


    </script>
</head>
<body>
    <form name="frm">
        <input type="text" name="txtH" value="0" size="2"/>
        <input type="text" name="txtM" value="0" size="2"/>
        <input type="text" name="txtS" value="0" size="2"/>
        <br /><br />
        <input type="button" value="Start" onclick="fn_sample();" />
    </form>
</body>

Upvotes: 3

Views: 75

Answers (1)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70822

Just add else after the close brace, to make setTimeout depending on previous test.

(For demo, I've reduced timeout to 100 to wait 6 seconds instead of 60;-). Note for ensuring there in never more than 1 second for a full loop, you can't sleep 1 second between each operation! Prefer to use : window.setTimeout("fn_sample()",1000-(new Date()%1000));. This will work until fn_sample() execution time come over 1 second.

        function fn_sample() {
            document.frm.txtS.value = parseInt(document.frm.txtS.value) + 1;
            var t1 = document.frm.txtS.value;
            if(t1>=60){

                document.frm.txtS.value = 0;

            } else
            window.setTimeout("fn_sample()",
                              100-(new Date()%100));

        }
    <form name="frm">
        <input type="text" name="txtH" value="0" size="2"/>
        <input type="text" name="txtM" value="0" size="2"/>
        <input type="text" name="txtS" value="0" size="2"/>
        <br /><br />
        <input type="button" value="Start" onclick="fn_sample();" />
    </form>

Upvotes: 1

Related Questions