Timer-Case Analysis in JS

Keywords: Front-end Javascript JSP Windows

Making js timer

In javascritp, there are two special functions for timers:

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

The first parameter,'function()', is the action to be performed when the timer triggers. It can be a function or several functions separated by';'.For example, to pop up two warning windows, you can replace "function();"
"alert('first warning window!'); alert('second warning window!'); and the second parameter"delaytime"is the interval time in milliseconds, that is, filling in"5000", which means 5 seconds.   

A countdown timer triggers events after a specified time has arrived, while a cycle timer triggers events repeatedly when an interval arrives. The difference between the two is that the former acts only once, while the latter acts continuously.

For example, if you open a page and want to jump to another page automatically a few seconds apart, you need to use the countdown timer "setTimeout" ("function;") and if you want to set a sentence to appear in one word, The cycle timer "setInterval" ("function (;") is required.

document.activeElement.id is used to get the focus of the form.Use if to determine if the document.activeElement.id and form IDs are the same. For example, if ("mid"== document.activeElement.id) {alert();}, "mid" is the ID of the form.

Timer: Used to specify that a program is executed after a specific period of time.

Timed Execution in JS, Differences between setTimeout and setInterval, and l Release Method

setTimeout(Expression,DelayTime), after DelayTime, executes an Expression, which is used to delay a period of time before performing an operation.
setTimeout("function",time) sets a timeout object

setInterval(expression,delayTime), each DelayTime, executes Expression. It is often used to refresh expressions.
setInterval("function",time) sets a timeout object

SetInterval is automatic and setTimeout does not repeat.

ClearTimeout (object) Clears the set Timeout object
 ClearInterval (object) Clears the set Interval object

Two examples are given.

Example 1. Word by word output string when form triggers or loads

The code is as follows:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Untitled Document</title>
<script language="JavaScript" type="text/javascript">
var str = "This is sample text for testing";
var seq = 0;
var second=1000; //1 second interval
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, check the input box information regularly. When the focus is not on, do not perform the check action.

The code is as follows:

<!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>Untitled Document</title>
<script language="JavaScript" type="text/javascript">
var second=5000; //5 seconds interval
var c=0;
function scroll() {
c++;
if ("b" == document.activeElement.id) {
var str="Timing check<b> "+c+" </b>second<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. A warning window pops up when the timer time has arrived.

The code is as follows:

<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="Timing has started!";
setTimeout("alert('Ten seconds to!')",10000)
}
</script>
<body>
<div id="m"></div>
<input TYPE="button" value=" Timing Start" onclick="count()">
</body>
</html>

Example 4: Countdown timer jump

The code is as follows:

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

Example 6:

The code is as follows:

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

Example 7:

The code is as follows:

<script language="javascript" type="text/javascript">
 setTimeout("window.location.href='b.html'", 2000);
 //Both of the following are available
 //setTimeout("javascript:location.href='b.html'", 2000);
 //setTimeout("window.location='b.html'", 2000);
</script>

Example 8:

The code is as follows:

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

js timer (execute once, repeat)

Share a piece of js code, a small example of a js timer, divided into a timer that executes once and a timer that repeats.For beginners.

1, Timer that executes only once

The code is as follows:

<script>  
//Timer runs asynchronously  
function hello(){  
    alert("hello");  
}  
//Execute method using method name  
var t1 = window.setTimeout(hello,1000);  
var t2 = window.setTimeout("hello()",3000);//Execute method using string  
window.clearTimeout(t1);//Remove timer  
</script>

2. Duplicate timer

The code is as follows:

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

Remarks:

If there are two methods in a page that are executed after the page is loaded, but they are not executed in sequence, you can solve them by referring to the following methods: You can add a timer to the onload method, set a timer, and delay it for a while before running, so you can think of it as distinguishing the order in which the page loading methods are run.

The code is as follows:

<!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+"Success in seconds')",secondsYC*1000);
        }
        catch(e)
        {
            alert("Please enter the correct number of seconds.");
        }
    }
    function overYC()
    {
        clearTimeout(YC);
        YC=null;
        alert("Termination delay succeeded.");
    }

/**************************↓↓↓↓Timer use********************************************************/

    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 have successfully reached 10 seconds");
            return;
        }
        sn.innerHTML=parseInt(sn.innerHTML,10)+1;
    }

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        //Delayer use: </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 Delay" />
        <input type="button" id="Button1" onclick="javascript:alert('good monrning');" value="Ordinary pop-up window" />
    </div>
    <br />
    <div>
        //Timer use: </div>
    <div>
    <div id="sn">0</div>
    <label id="Label1" title="Fixed interval seconds:"></label>
        <input type="text" id="txtIntervalSeconds" value="1" />
        <input type="button" id="btnBDS" onclick="javascript:beginDS()" value="Start Timer" />
        <input type="button" id="btnODS" onclick="javascript:overDS()" value="Termination Timing" />
        <input type="button" id="btnGDS" onclick="javascript:goonDS()" value="Continue timing" />

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

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

Posted by Akenatehm on Wed, 25 Mar 2020 01:06:50 -0700