Home > Web Front-end > JS Tutorial > body text

Detailed explanation of usage examples of timers in JavaScript

黄舟
Release: 2017-11-18 14:11:54
Original
1905 people have browsed it

In our previous article, we introduced you to the principles of Timer in JavaScript. I believe that many guys have a better understanding of the work of JavaScript timers. , now that we know the principle, let us introduce to you the use of timers in JavaScript!

In javascriptp, there are two special functions for timers, which are:

##1. Countdown timer:

timename=setTimeout("function();",delaytime);
Copy after login

2. Loop timer:

timename=setInterval("function();",delaytime);
Copy after login

The first parameter "function()" is the action to be performed when the timer is triggered. It can be one function or several Functions can be separated by ";". For example, if you want to pop up two warning windows, you can replace "function();" with

"alert('First warning window!');alert('Second warning window!');"; and The second parameter "delaytime" is the interval time in milliseconds, that is, filling in "5000" means 5 seconds.
The countdown timer triggers an event after the specified time arrives, while the loop timer triggers the event repeatedly when the interval arrives. The difference between the two is that the former only works once, while the latter works continuously.
For example, after you open a page and want to automatically jump to another page every few seconds, you need to use the countdown timer "setTimeout("function();",delaytime)", and if you want to set a certain To set a sentence to appear one word at a time,
you need to use the loop timer "setInterval("function();",delaytime)".

To obtain the focus of the form, use

document.activeElement.id. Use if to determine whether document.activeElement.id and the form's ID are the same. For example: if ("mid" == document.activeElement.id) {alert();}, "mid" is the ID corresponding to the form.

Timer:

Used to specify the execution of a certain program after a specific period of time.

Timing execution in JS, the difference between setTimeout and setInterval, and the cancellation method

setTimeout(Expression, DelayTime), after DelayTime, Expression will be executed once, and setTimeout is used to delay for a period of time. Do something again.

setTimeout("function",time) Set a timeout object

setInterval(expression, delayTime), each DelayTime will execute Expression. It can often be used to refresh

expression. setInterval("function",time) Set a timeout object

SetInterval is automatically repeated, and setTimeout will not be repeated.

clearTimeout(object) clears the setTimeout object

clearInterval(object) clears the setInterval object

Two examples are given.

Example 1. When the form is triggered or loaded, output the
string verbatim

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script language="JavaScript" type="text/javascript">
var str = "这个是测试用的范例文字";
var seq = 0;
var second=1000; //间隔时间1秒钟
function scroll() {
msg = str.substring(0, seq+1);
document.getElementByIdx_x_x(&#39;word&#39;).innerHTML = msg;
seq++;
if (seq >= str.length) seq = 0;
}
</script>
</head>
<body onload="setInterval(&#39;scroll()&#39;,second)">
<p id="word"></p><br/><br/>
</body>
</html>
Copy after login

Example 2. When the focus is on the input box, check the input box information regularly. When the focus is not on No check action is performed.

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>无标题文档</title>
<script language="JavaScript" type="text/javascript">
var second=5000; //间隔时间5秒钟
var c=0;
function scroll() {
c++;
if ("b" == document.activeElement.id) {
var str="定时检查第<b> "+c+" </b>次<br/>";
if(document.getElementByIdx_x_x(&#39;b&#39;).value!=""){
str+="输入框当前内容为当前内容为<br/><b> "+document.getElementByIdx_x_x(&#39;b&#39;).value+"</b>";
}
document.getElementByIdx_x_x(&#39;word&#39;).innerHTML = str;
}
}
</script>
</head>
<body>
<textarea id="b" name="b" style="height:100px; width:300px;" onfocus="setInterval(&#39;scroll()&#39;,second)"></textarea><br/><br/>
<p id="word"></p><br/><br/>
</body>
</html>
Copy after login

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

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(&#39;m&#39;).innerHTML="计时已经开始!";
setTimeout("alert(&#39;十秒钟到!&#39;)",10000)
}
</script>
<body>
<p id="m"></p>
<input TYPE="button" value=" 计时开始" onclick="count()">
</body>
</html>
Copy after login

Example 4: Countdown time jump


The code is as follows:

<html>
<head>
  <base href="<%=basePath%>">
  <title>My JSP &#39;ds04.jsp&#39; starting page</title>
  <span id="tiao">3</span>
  <a href="javascript:countDown"> </a>秒后自动跳转……
  <meta http-equiv=refresh content=3;url= &#39;/ds02.jsp&#39;/>
  <!--脚本开始-->
  <script language="javascript" type="">
function countDown(secs){
 tiao.innerText=secs;
 if(--secs>0)
  setTimeout("countDown("+secs+")",1000);
 }
 countDown(3);
 </script>
  <!--脚本结束-->
 </head>
Copy after login

Example 6:

The code is as follows:

<head> 
    <meta http-equiv="refresh" content="2;url=&#39;b.html&#39;"> 
</head>
Copy after login

Example 7:

The code is as follows:

<script language="javascript" type="text/javascript">
 setTimeout("window.location.href=&#39;b.html&#39;", 2000);
 //下面两个都可以用
 //setTimeout("javascript:location.href=&#39;b.html&#39;", 2000);
 //setTimeout("window.location=&#39;b.html&#39;", 2000);
</script>
Copy after login

Example 8:

The code is as follows:

<span id="totalSecond">2</span>
<script language="javascript" type="text/javascript">
 var second = document.getElementByIdx_x(&#39;totalSecond&#39;).innerHTML;
 if(isNaN(second)){
  //……不是数字的处理方法
 }else{
  setInterval(function(){
   document.getElementByIdx_x(&#39;totalSecond&#39;).innerHTML = --second;
   if (second <= 0) {
    window.location = &#39;b.html&#39;;
   }
  }, 1000);
 } 
</script>
Copy after login

js timer (execute once, repeat execution)

Share a piece of js code, a small example of js timer, which is divided into a timer that executes once and a timer that executes repeatedly. For reference for beginners.

1, the timer that only executes once

The code is as follows:

<script>  
//定时器 异步运行  
function hello(){  
    alert("hello");  
}  
//使用方法名字执行方法  
var t1 = window.setTimeout(hello,1000);  
var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法  
window.clearTimeout(t1);//去掉定时器  
</script>
Copy after login

2, the timer that executes repeatedly

The code is as follows:

<script>  
function hello(){  
    alert("hello");  
}  
//重复执行某个方法  
var t1 = window.setInterval(hello,1000);  
var t2 = window.setInterval("hello()",3000);  
//去掉定时器的方法  
window.clearInterval(t1);  
</script>
Copy after login

Remarks:

If there are two methods on a page, both of which are executed after the page is loaded, but actually cannot be executed in order, you can refer to the following method to solve the problem:

Yes Add a timer in the onload method, set a timer, and "delay" it for a period of time before running it. This can be considered to distinguish the order of page loading and running methods.

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(&#39;延迟"+secondsYC+"秒成功&#39;)",secondsYC*1000);
        }
        catch(e)
        {
            alert("请输入正确的秒数。");
        }
    }
    function overYC()
    {
        clearTimeout(YC);
        YC=null;
        alert("终止延迟成功。");
    }

/**************************↓↓↓↓定时器的使用↓↓↓↓********************************/

    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("恭喜你,已成功达到10秒");
            return;
        }
        sn.innerHTML=parseInt(sn.innerHTML,10)+1;
    }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <p>
        延迟器的使用:</p>
    <p>
     <label id="Label2" title="延迟秒数:"></label>
        <input type="text" id="txtYCSeconds" value="3" />
        <input type="button" id="btnBYC" onclick="javascript:beginYC()" value="开始延迟" />
        <input type="button" id="btnOYC" onclick="javascript:overYC()" value="终止延迟" />
        <input type="button" id="Button1" onclick="javascript:alert(&#39;good monrning&#39;);" value="普通弹窗" />
    </p>
    <br />
    <p>
        定时器的使用:</p>
    <p>
    <p id="sn">0</p>
    <label id="Label1" title="定时间隔秒数:"></label>
        <input type="text" id="txtIntervalSeconds" value="1" />
        <input type="button" id="btnBDS" onclick="javascript:beginDS()" value="启动定时" />
        <input type="button" id="btnODS" onclick="javascript:overDS()" value="终止定时" />
        <input type="button" id="btnGDS" onclick="javascript:goonDS()" value="继续定时" />

        <label id="ds" title="延迟秒数:"></label>
        <input type="text" id="txtDDSSeconds" value="5" />
        <input type="button" id="btnDDS" onclick="javascript:delayDS()" value="延迟定时" />

        </p>
    </form>
</body>
</html>
Copy after login

Summary:

We learned about JavaScript timers in the previous article Under the principle of , and based on the usage introduction in this article, I believe that everyone can master the use of timers in JavaScript. I hope it will be helpful to your work!

related suggestion:

About the analysis of the principle of timer in JavaScript


About setTimeout in JavaScript timer Detailed explanation of () and setInterval()


##Javascript timer example code


JavaScript timer demo

The above is the detailed content of Detailed explanation of usage examples of timers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template