Home  >  Article  >  Web Front-end  >  The use of js timer (explanation with examples)_javascript skills

The use of js timer (explanation with examples)_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:05:16909browse

In javascript, there are two dedicated functions for timers, namely:

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 To set a sentence to appear one word at a time,
requires the use of 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:
is used to specify a program to be executed 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, an Expression will be executed. setTimeout is used to delay for a period of time before performing an operation.
setTimeout("function",time) sets a timeout object

setInterval(expression, delayTime), Expression will be executed for each DelayTime. It can often be used to refresh expressions.
setInterval("function", time) sets 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

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

Copy code The code is as follows:




Untitled Document








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:




< title>Untitled document












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

Copy code The code is as follows:




< ;script language="javascript">
function count() {
document.getElementByIdx_x_x('m').innerHTML="Timer has started!";
setTimeout("alert('Ten seconds to! ')",10000)
}



< input TYPE="button" value=" Timing starts" onclick="count()">


Example 4: Countdown time jump

Copy code The code is as follows:




My JSP 'ds04.jsp' starting page</ title><br> <span id="tiao">3</span><br> <a href="javascript:countDown"> </a>Automatically jump after seconds...<br> <meta http-equiv=refresh content=3;url= '/ds02.jsp'/><br> <!--Start script--><br> <script language="javascript" type= ""><br>function countDown(secs){<br> tiao.innerText=secs;<br> if(--secs>0)<br> setTimeout("countDown(" secs ")",1000); <br> }<br> countDown(3);<br> </script><br> <!--End of script--><br> </head><br> </div> <br><br>Example 6: <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="44219" class="copybut" id="copybut44219" onclick="doCopy('code44219')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code44219"> <br><head> <br> <meta http- equiv="refresh" content="2;url='b.html'"> <br></head> <br> </div> <p>Example 7:</p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="26465" class="copybut" id="copybut26465" onclick="doCopy('code26465')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code26465"> <br><script language="javascript" type="text /javascript"><br> setTimeout("window.location.href='b.html'", 2000);<br> //Both of the following two can be used<br> //setTimeout("javascript:location. href='b.html'", 2000);<br> //setTimeout("window.location='b.html'", 2000);<br></script><br> </div> <p>Example 8:</p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="53168" class="copybut" id="copybut53168" onclick="doCopy('code53168')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code53168"> <br><span id="totalSecond">2< /span><br><script language="javascript" type="text/javascript"><br> var second = document.getElementByIdx_x('totalSecond').innerHTML;<br> if(isNaN(second)) {<br> //...not a number processing method<br> }else{<br> setInterval(function(){<br> document.getElementByIdx_x('totalSecond').innerHTML = --second;<br> if (second <= 0) {<br> window.location = 'b.html';<br> }<br> }, 1000);<br> } <br></script><br> </div> <p>js timer (execute once, repeat)</p> <p>Share a piece of js code, a small example of js timer, which is divided into a timer that is executed once and a timer that is executed repeatedly. For reference for beginners. </p> <p>1, a timer that only executes once </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="73058" class="copybut" id="copybut73058" onclick="doCopy('code73058')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code73058"> <br><script> <br>//Timer asynchronous Run <br>function hello(){ <br> alert("hello"); <br>} <br>//Use the method name to execute the method <br>var t1 = window.setTimeout(hello,1000); <br>var t2 = window.setTimeout("hello()",3000);//Use string execution method <br>window.clearTimeout(t1);//Remove the timer <br></script><br> </div> <p>2, timer for repeated execution</p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="39946" class="copybut" id="copybut39946" onclick="doCopy('code39946')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code39946"> <br><script> <br>function hello(){ <br> alert("hello"); <br>} <br>//Repeatedly execute a method <br>var t1 = window. setInterval(hello,1000); <br>var t2 = window.setInterval("hello()",3000); <br>//How to remove the timer <br>window.clearInterval(t1); <br>&lt ;/script><br> </div> <p>Remarks: </p> <p>If there are two methods in 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: <br>You can add a timer in the onload method , set a timer, "delay" for a period of time before running, which can be considered to distinguish the order of page loading and running methods. </p> <p><br><br></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="39283" class="copybut" id="copybut39283" onclick="doCopy('code39283')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code39283"> <br><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br><html xmlns="http://www.w3.org/1999/xhtml"><br><head runat="server"><br>    <title>Untitled Page</title> <p>    <script language="javascript" type="text/javascript"><br>    var YC = new Object();<br>    function beginYC()<br>    {<br>        var secondsYC = document.getElementById("txtYCSeconds").value;<br>        try<br>        { <br>            YC = setTimeout("alert('延迟"+secondsYC+"秒成功')",secondsYC*1000);<br>        }<br>        catch(e)<br>        {<br>            alert("请输入正确的秒数。");<br>        }<br>    }<br>    function overYC()<br>    {<br>        clearTimeout(YC);<br>        YC=null;<br>        alert("终止延迟成功。");<br>    }<br><br>/**************************↓↓↓↓定时器的使用↓↓↓↓********************************/<br><br>    var timerDS = new Object();<br>    var timerDDS = new Object();<br>    function beginDS()<br>    {<br>        sn.innerHTML = "0";<br>        timerDS = setInterval("addOne()",parseInt(document.getElementById("txtIntervalSeconds").value,10)*1000);<br>    }<br>    function goonDS()<br>    {<br>        timerDS = setInterval("addOne()",parseInt(document.getElementById("txtIntervalSeconds").value,10)*1000);<br>    }<br>    function overDS()<br>    {<br>        clearInterval(timerDS);<br>        timerDS=null;<br>    }<br>    function delayDS()<br>    {<br>        overDS();<br>        timerDDS = setTimeout("goonDS()",document.getElementById("txtDDSSeconds").value*1000);<br>    }<br>    function addOne()<br>    {<br>        if(sn.innerHTML=="10")<br>        {<br>            overDS();<br>            alert("恭喜你,已成功达到10秒");<br>            return;<br>        }<br>        sn.innerHTML=parseInt(sn.innerHTML,10)+1;<br>    }<br><br>    </script></p> <p></head><br><body><br>    <form id="form1" runat="server"><br>    <div><br>        延迟器的使用:</div><br>    <div><br>     <label id="Label2" title="延迟秒数:"></label><br>        <input type="text" id="txtYCSeconds" value="3" /><br>        <input type="button" id="btnBYC" onclick="javascript:beginYC()" value="开始延迟" /><br>        <input type="button" id="btnOYC" onclick="javascript:overYC()" value="终止延迟" /><br>        <input type="button" id="Button1" onclick="javascript:alert('good monrning');" value="普通弹窗" /><br>    </div><br>    <br /><br>    <div><br>        定时器的使用:</div><br>    <div><br>    <div id="sn">0</div><br>  <label id="Label1" title="Timer interval seconds:"></label><br> > btnODS" onclick="javascript:overDS()" value="Terminate timing" /><br>   <input type="button" id="btnGDS" onclick="javascript:goonDS()" value="Continue timing " /><br><br>  <label id="ds" title="Delay seconds:"></label><br> ="5" /><br>                                                                                                                                                        div><br> </form><br></body><br></html><br><br><br></p> </div> </div></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>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</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="DataGrid result set clearing method in EasyUI component under Jquery_jquery" href="http://m.php.cn/faq/14539.html">DataGrid result set clearing method in EasyUI component under Jquery_jquery</a></span><span>Next article:<a class="dBlack" title="DataGrid result set clearing method in EasyUI component under Jquery_jquery" href="http://m.php.cn/faq/14541.html">DataGrid result set clearing method in EasyUI component under Jquery_jquery</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="http://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ul class="nphpXgwzList"><li><b></b><a href="http://m.php.cn/faq/1609.html" title="An in-depth analysis of the Bootstrap list group component" class="aBlack">An in-depth analysis of the Bootstrap list group component</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1640.html" title="Detailed explanation of JavaScript function currying" class="aBlack">Detailed explanation of JavaScript function currying</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1949.html" title="Complete example of JS password generation and strength detection (with demo source code download)" class="aBlack">Complete example of JS password generation and strength detection (with demo source code download)</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2248.html" title="Angularjs integrates WeChat UI (weui)" class="aBlack">Angularjs integrates WeChat UI (weui)</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2351.html" title="How to quickly switch between Traditional Chinese and Simplified Chinese with JavaScript and the trick for websites to support switching between Simplified and Traditional Chinese_javascript skills" class="aBlack">How to quickly switch between Traditional Chinese and Simplified Chinese with JavaScript and the trick for websites to support switching between Simplified and Traditional Chinese_javascript skills</a><div class="clear"></div></li></ul></div></div><div class="nphpFoot"><div class="nphpFootBg"><ul class="nphpFootMenu"><li><a href="http://m.php.cn/"><b class="icon1"></b><p>Home</p></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><p>Course</p></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><p>Q&A</p></a></li><li><a href="http://m.php.cn/login"><b class="icon5"></b><p>My</p></a></li><div class="clear"></div></ul></div></div><div class="nphpYouBox" style="display: none;"><div class="nphpYouBg"><div class="nphpYouTitle"><span onclick="$('.nphpYouBox').hide()"></span><a href="http://m.php.cn/"></a><div class="clear"></div></div><ul class="nphpYouList"><li><a href="http://m.php.cn/"><b class="icon1"></b><span>Home</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><span>Course</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/article.html"><b class="icon3"></b><span>Article</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><span>Q&A</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/dic.html"><b class="icon6"></b><span>Dictionary</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course/type/99.html"><b class="icon7"></b><span>Manual</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/xiazai/"><b class="icon8"></b><span>Download</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/faq/zt" title="Topic"><b class="icon12"></b><span>Topic</span><div class="clear"></div></a></li><div class="clear"></div></ul></div></div><div class="nphpDing" style="display: none;"><div class="nphpDinglogo"><a href="http://m.php.cn/"></a></div><div class="nphpNavIn1"><div class="swiper-container nphpNavSwiper1"><div class="swiper-wrapper"><div class="swiper-slide"><a href="http://m.php.cn/" >Home</a></div><div class="swiper-slide"><a href="http://m.php.cn/article.html" class="hover">Article</a></div><div class="swiper-slide"><a href="http://m.php.cn/wenda.html" >Q&A</a></div><div class="swiper-slide"><a href="http://m.php.cn/course.html" >Course</a></div><div class="swiper-slide"><a href="http://m.php.cn/faq/zt" >Topic</a></div><div class="swiper-slide"><a href="http://m.php.cn/xiazai" >Download</a></div><div class="swiper-slide"><a href="http://m.php.cn/game" >Game</a></div><div class="swiper-slide"><a href="http://m.php.cn/dic.html" >Dictionary</a></div><div class="clear"></div></div></div><div class="langadivs" ><a href="javascript:;" class="bg4 bglanguage"></a><div class="langadiv" ><a onclick="javascript:setlang('zh-cn');" class="language course-right-orders chooselan " href="javascript:;"><span>简体中文</span><span>(ZH-CN)</span></a><a onclick="javascript:;" class="language course-right-orders chooselan chooselanguage" href="javascript:;"><span>English</span><span>(EN)</span></a><a onclick="javascript:setlang('zh-tw');" class="language course-right-orders chooselan " href="javascript:;"><span>繁体中文</span><span>(ZH-TW)</span></a><a onclick="javascript:setlang('ja');" class="language course-right-orders chooselan " href="javascript:;"><span>日本語</span><span>(JA)</span></a><a onclick="javascript:setlang('ko');" class="language course-right-orders chooselan " href="javascript:;"><span>한국어</span><span>(KO)</span></a><a onclick="javascript:setlang('ms');" class="language course-right-orders chooselan " href="javascript:;"><span>Melayu</span><span>(MS)</span></a><a onclick="javascript:setlang('fr');" class="language course-right-orders chooselan " href="javascript:;"><span>Français</span><span>(FR)</span></a><a onclick="javascript:setlang('de');" class="language course-right-orders chooselan " href="javascript:;"><span>Deutsch</span><span>(DE)</span></a></div></div><script> var swiper = new Swiper('.nphpNavSwiper1', { slidesPerView : 'auto', observer: true,//修改swiper自己或子元素时,自动初始化swiper observeParents: true,//修改swiper的父元素时,自动初始化swiper }); </script></div></div><!--顶部导航 end--><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body></html>