Home  >  Article  >  Web Front-end  >  js timer (execute once, repeat execution)_javascript skills

js timer (execute once, repeat execution)_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:56:291120browse

1. A timer that only executes once

Copy code The code is as follows:

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



2, timer for repeated execution

Copy code The code is as follows:

<script> <br>function hello(){ <br>alert("hello"); <br>} <br>//Repeat 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></script>


Note:

If there are two methods in a page, both are in the page It is executed after the loading is completed, but it actually fails to be executed in order. You can refer to the following methods 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. It is considered to distinguish the order of page loading and running methods.

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:

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><br> </div> <br>Example 6:<br> <p></p> <div class="codetitle"><span><a style="CURSOR: pointer" data="16541" class="copybut" id="copybut16541" onclick="doCopy('code16541')">Copy code<u></u></a> The code is as follows:</span></div> <div class="codebody" id="code16541"><head> <br> <meta http- equiv="refresh" content="2;url='b.html'"> <br></head> <br><br> </div> Example 7:<p> </p> <p></p> <div class="codetitle"><span><a style="CURSOR: pointer" data="36431" class="copybut" id="copybut36431" onclick="doCopy('code36431')">Copy code<u></u></a> The code is as follows:</span></div> <div class="codebody" id="code36431"><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><br> </div> Example 8:<p> </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="3319" class="copybut" id="copybut3319" onclick="doCopy('code3319')">Copy code<u></u></a> The code is as follows:</span><div class="codebody" id="code3319"> <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>  //……不是数字的处理方法<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> </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="A simple example of JS judging text box content change event_javascript skills" href="http://m.php.cn/faq/13733.html">A simple example of JS judging text box content change event_javascript skills</a></span><span>Next article:<a class="dBlack" title="A simple example of JS judging text box content change event_javascript skills" href="http://m.php.cn/faq/13735.html">A simple example of JS judging text box content change event_javascript skills</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><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="http://m.php.cn/about/us.html">About us</a><a href="http://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="http://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><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>