A detailed explanation of setinterval and settimeout usage in JavaScript

Source: Internet
Author: User
Tags repetition setinterval

In the writing H5 game often need to use the Timed Refresh page to achieve the animation effect, more commonly known as settimeout () and setinterval (), but everyone on the use of setinterval and settimeout understand, The following through this article for everyone to explain the use of JS in SetInterval and settimeout, need to refer to the friend

SetTimeout

Describe

SetTimeout (CODE,MILLISEC)

The SetTimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds.

Note: During the call, you can use Cleartimeout (id_of_settimeout) to terminate

Parameters Description
Code Required, the JavaScript code string to execute after the function to be called.
Millisec Required, the number of milliseconds to wait before executing the code.

Settimeinterval

SetInterval (code,millisec[, "Lang"])

Parameters Description
Code Required, the function to invoke or the code string to execute.
Millisec Required, the time interval between periodic execution or calling code, in milliseconds.

The SetInterval () method invokes a function or evaluates an expression according to the specified period (in milliseconds).

JS Set delay:

Using setinterval and setting the delay function settimeout very similar. SetTimeout used to delay a period of time before doing an operation.

SetTimeout ("function", time) sets a timeout object SetInterval ("function", time) sets a timeout object

SetInterval for automatic repetition, settimeout does not repeat.

Cleartimeout (object) clears the set SetTimeout object Clearinterval (object) clears the SetInterval object that has been set

The SetInterval () method invokes a function or evaluates an expression according to the specified period (in milliseconds).

Using timers to implement deferred execution of JavaScript or to repeat the Window object provides two ways to achieve the effect of the timer, respectively Window.settimeout () and Window.setinterval. The former allows a piece of code to run after a specified time, while the latter allows a piece of code to run once every specified time. Their prototypes are as follows: Window.settimeout (expression,milliseconds); Window.setinterval (Expression,milliseconds); Where expression can be a piece of code enclosed in quotation marks, or a function name, the function is automatically called when the function name is used as the invocation handle, and when a string is used, it can be written to the parameter to be passed. The second parameter of two methods is milliseconds, which indicates the number of milliseconds to delay or repeat execution.

Two methods are described below.

1. Window.settimeout method The method can defer execution of a function, for example:

?
12345 <script language="JavaScript"type="text/javascript"><!-- functionhello(){ alert("hello"); } window.setTimeout(hello,5000);//--> </script>

This code will cause the page to open 5 seconds after the dialog "Hello" is displayed. The last sentence can also be written as: Window.settimeout ("Hello ()", 5000); Readers can appreciate their differences, and in the Window.setinterval method there is the same nature. If you cancel deferred execution before the delay period arrives, you can use the Window.cleartimeout (Timeoutid) method, which receives an ID that represents a timer. This ID is returned by the SetTimeout method, for example:

?
1234567891011 <script language= Code class= "JS string" > "JavaScript" type= "text/ JavaScript " > <!-- function hello () {   alert ( "Hello" } var id=window.settimeout ( hello,5000); document.onclick= function () {   window.cleartimeout (ID); &NBSP; //--> </script>

This way, if you want to suppress the display, simply click on any part of the page and execute the Window.cleartimeout method, which causes the timeout operation to be canceled.

2. Window.setinterval method This method allows a function to be called once every fixed time, which is a very common method. If you want to cancel timed execution, similar to the Cleartimeout method, you can call the Window.clearinterval method. The Clearinterval method also receives a value returned by the SetInterval method as a parameter. For example://define a recurring call to Var id=window.setinterval ("somefunction", 10000); Cancel timed execution of Window.clearinterval (ID); The above code is only used to illustrate how to cancel a timed execution. In fact, in many cases need to use the SetInterval method, the following will design a stopwatch, to describe the purpose of the SetInterval function: The stopwatch will include two buttons and a text box to display the time. When the Start button is clicked, the minimum unit is 0.01 seconds, when the button is clicked again to stop the timing, and the text box displays the elapsed time. Another button is used to clear the current time. The implementation code is as follows:

?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  <title> New Document </title> <body> <form action="somepage.asp"> <input type="text" value="0" name="txt1"/> <input type="button" value="开始" name="btnStart"/> <input type="button" value="重置" name="btnReset"/> </form> </body> <script language="JavaScript" type="text/javascript"><!--//获取表单中的表单域var txt=document.forms[0].elements["txt1"]; var btnStart=document.forms[0].elements["btnStart"]; var btnReset=document.forms[0].elements["btnReset"] //定义定时器的idvar id;//每10毫秒该值增加1var seed=0;btnStart.onclick=function(){   //根据按钮文本来判断当前操作    if(this.value=="开始"){        //使按钮文本变为停止        this.value="停止";       //使重置按钮不可用        btnReset.disabled=true;       //设置定时器,每0.01s跳一次       id=window.setInterval(tip,10);    }else{       //使按钮文本变为开始       this.value="开始";       //使重置按钮可用        btnReset.disabled=false;       //取消定时       window.clearInterval(id);    } }//重置按钮btnReset.onclick=function(){   seed=0; }//让秒表跳一格 function tip(){    seed++;    txt.value=seed/100;}//--></script>

Passing parameters to a timer call, whether window.settimeout or window.setinterval, cannot take arguments when using the function name as the invocation handle, and in many cases it is necessary to have parameters, which requires a workaround. For example, function hello (_name), which is used to display a welcome message for the user name: Var username= "Jack";

?
1234 //根据用户名显示欢迎信息functionhello(_name){    alert("hello,"+_name); }

At this point, it is not feasible to attempt to use the following statement to delay the Hello function for 3 seconds:

Window.settimeout (Hello (userName), 3000);

This will cause the Hello function to execute immediately and pass the return value as the call handle to the SetTimeout function, and the result is not required by the program. You can achieve the desired result by using a string form:

Window.settimeout ("Hello (userName)", 3000);

The string here is a piece of JavaScript code, where username represents a variable. But this is not intuitive, and some occasions must use the function name, following a small trick to implement the call with the parameter function:

?
123456789101112 <script language="JavaScript" type="text/javascript"> <!-- var userName="jack";//根据用户名显示欢迎信息function hello(_name){    alert("hello,"+_name);}//创建一个函数,用于返回一个无参数函数function _hello(_name){    return function(){       hello(_name);    } }window.setTimeout(_hello(userName),3000); //--></script>

This defines a function _hello, which receives a parameter and returns a function with no parameters, using the parameters of the external function inside the function to invoke it without using parameters. In the Window.settimeout function, the function of parameter passing is achieved by using _hello (UserName) to return a function handle without parameters.

The Window object has two main timing methods, namely settimeout and setinteval their syntax is basically the same, but the completed function is different.

The SetTimeout method is a timed procedure, that is, what to do after what time. When you're done.

The SetInterval method is to represent the interval for a certain amount of time to perform an operation repeatedly.

  JS Set delay:

Using setinterval and setting the delay function settimeout very similar. SetTimeout used to delay a period of time before doing an operation.

SetTimeout ("function", time) sets a timeout object

SetInterval ("function", time) sets a timeout object

SetInterval for automatic repetition, settimeout does not repeat.

Cleartimeout (object) clears the SetTimeout object that has been set

Clearinterval (object) clears the SetInterval object that has been set

If you implement Setinerval functionality with settimeout, you will need to call yourself again and again in the program you are executing. If you want to purge counters that need to be different from the method used, call different cleanup methods:

For example:

?
12 tttt=setTimeout(‘northsnow()‘,1000);clearTimeout(tttt);

Or:

?
12 tttt=setInterval(‘northsnow()‘,1000);clearInteval(tttt);

To give an example:

?
1234567891011121314 <div id="liujincai"></div><input type="button" name="start" value="start" onclick=‘startShow();‘><input type="button" name="stop" value="stop" onclick="stop();"><script language="javascript"var intvalue=1;  var timer2=nullfunction startShow()  {    liujincai.innerHTML=liujincai.innerHTML + " " + (intvalue ++).toString();   timer2=window.setTimeout("startShow()",2000);  }  function stop()  {    window.clearTimeout(timer2);   }</script>

Or:

?
1234567891011121314 <div id="liujincai"></div><input type="button" name="start" value="start" onclick=‘timer2=window.setInterval("startShow()",2000);//startShow();‘><input type="button" name="stop" value="stop" onclick="stop();"><script language="javascript" var intvalue=1;  var timer2=null function startShow()  {    liujincai.innerHTML=liujincai.innerHTML + " " + (intvalue ++).toString();    function stop()  {    window.clearInterval(timer2);  }</script>

The above content is small to introduce to you about JavaScript in the use of setinterval and settimeout in detail, I hope that we learn setinterval and settimeout related knowledge has helped.

A detailed explanation of setinterval and settimeout usage in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.