The usage of SetInterval and setTimeout in JavaScript is described in detail.

Source: Internet
Author: User

The usage of SetInterval and setTimeout in JavaScript is described in detail.

SetTimeout

Description

SetTimeout (code, millisec)

The setTimeout () method is used to call a function or computing expression after a specified number of milliseconds.

Note: clearTimeout (id_of_settimeout) can be used to terminate a call.

Parameters Description
Code Required. The JavaScript code string to be executed 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 be called or the code string to be executed.
Millisec Required. The time interval between periodical execution or call codes, in milliseconds.

The setInterval () method can call functions or computation expressions according to the specified period (in milliseconds.

Set latency in JS:

SetInterval is similar to setTimeout. SetTimeout is used to perform an operation after a delay period.

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

SetInterval indicates automatic repetition, and setTimeout does not.

ClearTimeout (object) clears the set setTimeout object clearInterval (object) clears the set setInterval object

The setInterval () method can call functions or computation expressions according to the specified period (in milliseconds.

Using a timer to implement JavaScript deferred execution or repeated execution of window objects provides two methods to implement the timer effect, namely 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 time. Their prototype is as follows: window. setTimeout (expression, milliseconds); window. setInterval (expression, milliseconds); expression can be a piece of code enclosed in quotation marks or a function name. at the specified time, the system automatically calls the function, when a function name is used as the call handle, it cannot contain any parameters. When a string is used, you can write the parameters to be passed. The second parameter of the two methods is milliseconds, which indicates the number of milliseconds of delay or repeated execution.

The following describes two methods.

1. window. setTimeout method this method can delay the execution of a function, for example:

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

This code will enable the page to open for 5 seconds and then display the "hello" dialog box ". The last sentence can also be written as window. setTimeout ("hello ()", 5000). Readers can understand the differences between them, and the window. setInterval method also has such properties. If the execution is canceled before the delay period expires, you can use the window. clearTimeout (timeoutId) method, which receives an id, indicating a timer. This id is returned by the setTimeout method, for example:

<script language="JavaScript" type="text/javascript"><!--function hello(){   alert("hello");}var id=window.setTimeout(hello,5000);document.onclick=function(){   window.clearTimeout(id); }//--></script>

In this way, to cancel the display, you only need to click any part of the page to execute the window. clearTimeout method, so that the timeout operation is canceled.

2. window. setInterval: This method is a common method that allows a function to be called at regular intervals. To cancel scheduled execution, call the window. clearInterval method, similar to the clearTimeout method. The clearInterval method also receives the value returned by a setInterval method as a parameter. For example: // define a repeated call var id = window. setInterval ("somefunction", 10000); // cancel scheduled window execution. clearInterval (id); The above code is only used to describe how to cancel a scheduled execution. In fact, the setInterval method is used in many cases. Next we will design a stopwatch to introduce the purpose of the setInterval function: This stopwatch will contain two buttons and a text box for displaying time. Start timing when you click the start button. The minimum unit is 0.01 seconds. click the button again to stop timing. The text box displays the elapsed time. Another button is used to clear the current time. The implementation code is as follows:

<! Doctype html public "-// W3C // dtd html 4.0 Transitional // EN"> 

Call the timer to pass the parameter either window. setTimeout or window. setInterval: parameters are not allowed when the function name is used as the call handle, but must be included in many cases. This requires a solution. For example, for the hello (_ name) function, it is used to display the welcome information for the user name: var userName = "jack ";

// Display the welcome information based on the user name. function hello (_ name) {alert ("hello," + _ name );}

At this time, if you attempt to use the following statement to delay the hello function execution by 3 seconds, it is not feasible:

Window. setTimeout (hello (userName), 3000 );

This will enable the hello function to be executed immediately and pass the returned value to the setTimeout function as the call handle. The result is not required by the program. You can use a string to achieve the desired result:

Window. setTimeout ("hello (userName)", 3000 );

The string here is a piece of JavaScript code, where userName represents a variable. However, this method is not intuitive enough, and function names must be used in some cases. Here is a tips to call a function with parameters:

<Script language = "JavaScript" type = "text/javascript"> <! -- Var userName = "jack"; // display the welcome information according to the user name function hello (_ name) {alert ("hello," + _ name);} // create a function, returns a non-Parameter function _ hello (_ name) {return function () {hello (_ name) ;}} window. setTimeout (_ hello (userName), 3000); // --> </script>

A function _ hello is defined here, which is used to receive a parameter and return a function without a parameter. An external function parameter is used inside the function to call it, no parameters are required. In the window. setTimeout function, _ hello (userName) is used to return a function handle without parameters, thus implementing the function of passing parameters.

Window objects have two main timing Methods: setTimeout and setInteval. Their syntaxes are basically the same, but their functions are different.

The setTimeout method is a Timer Program, that is, after what time. After the job is finished, pull it down.

The setInterval method indicates that an operation is executed repeatedly at a certain interval.

  Set latency in JS:

SetInterval is similar to setTimeout. SetTimeout is used to perform an operation after a delay period.

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

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

SetInterval indicates automatic repetition, and setTimeout does not.

ClearTimeout (object) clears the set setTimeout object

ClearInterval (object) clears the set setInterval object

If you use setTimeout to implement the setInerval function, you need to regularly call yourself in the executed program. To clear a counter, you need to call different clearing methods based on the method used:

For example:

tttt=setTimeout('northsnow()',1000);clearTimeout(tttt);

Or:

tttt=setInterval('northsnow()',1000);clearInteval(tttt);

For example:

<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=null;  function startShow()  {    liujincai.innerHTML=liujincai.innerHTML + " " + (intvalue ++).toString();   timer2=window.setTimeout("startShow()",2000);  }  function stop()  {    window.clearTimeout(timer2);   }</script>

Or:

<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 a detailed explanation of the usage of SetInterval and setTimeout in JavaScript. I hope it will be helpful for you to learn about SetInterval and setTimeout.

Related Article

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.