Js timer using of instance

  • 2020-03-30 01:12:36
  • OfStack

In javascritp, there are two dedicated functions about the timer, respectively:

1. Counter timer: timename=setTimeout("function();" , delaytime);
2. Loop timer: timename=setInterval("function();" , delaytime);

The first parameter, "function()", is the action to be executed when the timer is triggered. It can be a function or several functions, with "; "between functions. Separate them. For example, to pop up two warning Windows, type "function();" Switch to
"Alert (' first warning window! '); Alert (' second warning window! ');" ; The second parameter "delaytime" is the interval time, in milliseconds, that is, fill in "5000", represents 5 seconds.
The difference between a countdown timer, which triggers events after the specified time has arrived, and a loop timer, which triggers events repeatedly when the interval has arrived, is that the former only works once, while the latter works continuously.
For example, when you open a page and want to automatically jump to another page within a few seconds, you need to use a backtimer "setTimeout("function();"). Delaytime), and if you want to set a sentence to appear one word at a time,
We need to use the loop timer "setInterval("function();" , delaytime) ".

Access to the focus of the form, then use document. ActiveElement. Id. To judge the document using the if. ActiveElement. To the same form of id and id.
Such as: the if (" mid "= = document. ActiveElement. Id) {alert (); },"mid" is the corresponding ID of the form.

Timer:
Used to specify the execution of a program after a specified period of time.

JS timing execution,setTimeout and setInterval differences, and l unwinding method

SetTimeout (Expression,DelayTime). After DelayTime, an Expression and a setTimeout will be executed for a delay of some time, and then an operation will be performed.
SetTimeout ("function",time) sets a timeout object

SetInterval (expression,delayTime), each delayTime, will execute expression. Often used to refresh expressions.
SetInterval ("function",time) sets a timeout object

SetInterval repeats automatically. SetTimeout does not repeat.

ClearTimeout (object) clears the setTimeout object that has been set
ClearInterval (object) clears the setInterval object that has been set

Just two examples.
Example 1. When a form is triggered or loaded, output a string verbatim


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title> Headless document </title>
<script language="JavaScript" type="text/javascript">
var str = " This is the sample text for the test ";
var seq = 0;
var second=1000; //The interval time is 1 second
function scroll() {
msg = str.substring(0, seq+1);
document.getElementByIdx_x_x('word').innerHTML = msg;
seq++;
if (seq >= str.length) seq = 0;
}
</script>
</head>
<body onload="setInterval('scroll()',second)">
<div id="word"></div><br/><br/>
</body>
</html>

 

Example 2. When the focus is on the input box, periodically check the input box information, and do not perform the check action when the focus is off.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title> Headless document </title>
<script language="JavaScript" type="text/javascript">
var second=5000; //The interval is 5 seconds
var c=0;
function scroll() {
c++;
if ("b" == document.activeElement.id) {
var str=" Timing control <b> "+c+" </b> time <br/>";
if(document.getElementByIdx_x_x('b').value!=""){
str+=" The current content of the input box is <br/><b> "+document.getElementByIdx_x_x('b').value+"</b>";
}
document.getElementByIdx_x_x('word').innerHTML = str;
}
}
</script>
</head>
<body>
<textarea id="b" name="b" style="height:100px; width:300px;" onfocus="setInterval('scroll()',second)"></textarea><br/><br/>
<div id="word"></div><br/><br/>
</body>
</html>

Example 3. The following is the simplest example, the warning window pops up after the timer time.


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script language="javascript">
function count() {
document.getElementByIdx_x_x('m').innerHTML=" The clock has started! ";
setTimeout("alert(' Ten seconds! ')",10000)
}
</script>
<body>
<div id="m"></div>
<input TYPE="button" value="  Timing begins " onclick="count()">
</body>
</html>

Example 4: countdown timed jump


<html>
<head>
  <base href="<%=basePath%>">
  <title>My JSP 'ds04.jsp' starting page</title>
  <span id="tiao">3</span>
  <a href="javascript:countDown"> </a> Automatic jump after seconds... 
  <meta http-equiv=refresh content=3;url= '/ds02.jsp'/>
  <!-- Script to start -->
  <script language="javascript" type="">
function countDown(secs){
 tiao.innerText=secs;
 if(--secs>0)
  setTimeout("countDown("+secs+")",1000);
 }
 countDown(3);
 </script>
  <!-- End of the script -->
 </head>


Example 6:


<head> 
    <meta http-equiv="refresh" content="2;url='b.html'"> 
</head> 

Example 7:


<script language="javascript" type="text/javascript">
 setTimeout("window.location.href='b.html'", 2000);
 //You can use both of the following
 //setTimeout("javascript:location.href='b.html'", 2000);
 //setTimeout("window.location='b.html'", 2000);
</script>

Example 8:


<span id="totalSecond">2</span>
<script language="javascript" type="text/javascript">
 var second = document.getElementByIdx_x('totalSecond').innerHTML;
 if(isNaN(second)){
  //... It's not a number
 }else{
  setInterval(function(){
   document.getElementByIdx_x('totalSecond').innerHTML = --second;
   if (second <= 0) {
    window.location = 'b.html';
   }
  }, 1000);
 } 
</script>

Js timer (execute once, execute repeatedly)

Share a piece of js code, about js timer small example, divided into the execution of a timer and repeated execution of the timer. For the novice friend reference.

1. The timer is executed only once


<script>  
//The timer runs asynchronously & NBSP;
function hello(){  
    alert("hello");  
}  
//Using the method name to execute the method & NBSP;
var t1 = window.setTimeout(hello,1000);  
var t2 = window.setTimeout("hello()",3000);//Using the string execution method & PI;
window.clearTimeout(t1);//Remove the timer & NBSP;
</script>

2, repeated execution of the timer


<script>  
function hello(){  
    alert("hello");  
}  
//Repeating a method & NBSP;
var t1 = window.setInterval(hello,1000);  
var t2 = window.setInterval("hello()",3000);  
//Method of removing the timer & NBSP;
window.clearInterval(t1);  
</script>

Remark:

If you have two methods in a page, both of which are executed after the page is loaded, but actually fail to execute in order, you can refer to the following solution:
You can add a timer to the onload method, set a timer, "delay" after a period of time to run, you can think of the page load method to distinguish the sequence.




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
    var YC = new Object();
    function beginYC()
    {
        var secondsYC = document.getElementById("txtYCSeconds").value;
        try
        { 
            YC = setTimeout("alert(' delay "+secondsYC+" S success ')",secondsYC*1000);
        }
        catch(e)
        {
            alert(" Please enter the correct number of seconds. ");
        }
    }
    function overYC()
    {
        clearTimeout(YC);
        YC=null;
        alert(" Abort delay successful. ");
    }



    var timerDS = new Object();
    var timerDDS = new Object();
    function beginDS()
    {
        sn.innerHTML = "0";
        timerDS = setInterval("addOne()",parseInt(document.getElementById("txtIntervalSeconds").value,10)*1000);
    }
    function goonDS()
    {
        timerDS = setInterval("addOne()",parseInt(document.getElementById("txtIntervalSeconds").value,10)*1000);
    }
    function overDS()
    {
        clearInterval(timerDS);
        timerDS=null;
    }
    function delayDS()
    {
        overDS();
        timerDDS = setTimeout("goonDS()",document.getElementById("txtDDSSeconds").value*1000);
    }
    function addOne()
    {
        if(sn.innerHTML=="10")
        {
            overDS();
            alert(" Congratulations, you've made it 10 seconds ");
            return;
        }
        sn.innerHTML=parseInt(sn.innerHTML,10)+1;
    }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         Use of retarding device: </div>
    <div>
     <label id="Label2" title=" Delay seconds: "></label>
        <input type="text" id="txtYCSeconds" value="3" />
        <input type="button" id="btnBYC" onclick="javascript:beginYC()" value=" Start delay " />
        <input type="button" id="btnOYC" onclick="javascript:overYC()" value=" Termination of the delay " />
        <input type="button" id="Button1" onclick="javascript:alert('good monrning');" value=" Normal popups " />
    </div>
    <br />
    <div>
         Use of timer: </div>
    <div>
    <div id="sn">0</div>
    <label id="Label1" title=" Timing interval seconds: "></label>
        <input type="text" id="txtIntervalSeconds" value="1" />
        <input type="button" id="btnBDS" onclick="javascript:beginDS()" value=" Start the timer " />
        <input type="button" id="btnODS" onclick="javascript:overDS()" value=" Termination of the timing " />
        <input type="button" id="btnGDS" onclick="javascript:goonDS()" value=" Continue to timing " />

        <label id="ds" title=" Delay seconds: "></label>
        <input type="text" id="txtDDSSeconds" value="5" />
        <input type="button" id="btnDDS" onclick="javascript:delayDS()" value=" The delay time " />

        </div>
    </form>
</body>
</html>


Related articles: