Home > Web Front-end > JS Tutorial > The use of js timer (explanation with examples)

The use of js timer (explanation with examples)

高洛峰
Release: 2017-02-08 16:21:53
Original
1519 people have browsed it

This article mainly introduces how to use timers in js. Friends in need can come here for reference, I hope it will be helpful to everyone

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

1. Countdown 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 one function or several functions. The 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, document.activeElement.id is used. 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 expressions.
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, the string is output verbatim


Copy code The code is as follows:

<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, and do not perform the checking action when the focus is not on.

Copy code 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.

Copy code 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

Copy code 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:

Copy code The code is as follows:

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

Example 7:

##Copy code 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:

Copy code 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 , divided into timers that are executed once and timers that are executed repeatedly. For reference for beginners.

1, a timer that only executes once

Copy code 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, a timer that executes repeatedly Device

Copy code 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

Note:

If there are two methods in one page, both It is executed after the page is loaded, but it is actually not executed in sequence. You can refer to the following method to solve the problem:

You can add a timer in the onload method, set a timer, and "delay" for a period of time before running again. , which can be considered to distinguish the order of page loading and running methods.

Copy code 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">
    <div>
        延迟器的使用:</div>
    <div>
     <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="普通弹窗" />
    </div>
    <br />
    <div>
        定时器的使用:</div>
    <div>
    <div id="sn">0</div>
    <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="延迟定时" />

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

更多js定时器的使用(实例讲解)相关文章请关注PHP中文网!

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