JavaScript timeout call and intermittent call instance tutorial

Source: Internet
Author: User
Tags numeric setinterval time in milliseconds

Intermittent call

Intermittent calls are common in JavaScript, setinterval, which is repeated calls over a certain amount of time.

The SetInterval () method receives two parameters: the first argument can be a string or a function, and the second parameter is a number in milliseconds, indicating the length of the recurrence interval.
argument is a string

When the first pass parameter is a string, the following:

SetInterval ("Alert (' is a string. ')", 1000);

The string here is a piece of JavaScript code, just like the parameters of the eval () function passed in, if there are two quotes inside and outside, remember that the quotes are not the same.

SetInterval () returns the ID of a numeric type, which is the unique identifier of the planned execution code, so you can use it to cancel the duplicate operation. SetInterval () corresponds to a method to cancel the operation: Clearinterval (), of course, to cancel the repeat operation, Clearinterval () must be placed before the completion of the time.

Like what:

var intervalid=setinterval (...);
Clearinterval (Intervalid);

First we get the ID, and then we pass the ID into clearinterval (), because the cancellation is immediately after setinterval (), so it can be canceled as soon as it doesn't happen.


parameter is a function

Because when the parameter is passed is a string, can cause performance loss, so in general, the most use or pass a function to it.

As follows:

var num=0;
function Increnum () {
num++;
if (num>=10) {
clearinterval (intervalid);
Alert (' over ');
}
Intervalid=setinterval (increnum,500);


The program sets a increnum function and passes it as a parameter to SetInterval (), and when it repeats to 10 times, cancels the operation and pops up the warning box.


Timeout call

Timeout and intermittent calls are similar, settimeout (), it also receives two parameters, the first can be a string containing JavaScript code, but also a function, the second parameter is the delay time and SetInterval () method parameters are the same.

But here's one thing to say:

Delay time is not to say that after the set delay, the program will certainly execute.

Why, then?

Because JavaScript is a single-threaded interpreter, you can only execute a piece of code within a certain amount of time, and you cannot execute multiple pieces of code simultaneously, so there is a task queue in JavaScript, and the tasks to be performed are queued in sequence, The set delay time is the time to add the current task to the task queue. If no task is currently executing, the code that is added to the task queue executes immediately, and if there is currently an executing code snippet, then the newly joined task is performed only when the code snippet is finished.

Similarly, settimeout () also has a return ID, which can also be canceled by this numeric ID, and the corresponding cancellation method is Cleartimeout ().

Here, we use the timeout call method to duplicate the repeated code in the intermittent call:

var num=0;
function Increnum () {
num++;
if (num<=10) {
settimeout (increnum,500);
}else{
alert (' over ');
}
settimeout (increnum,500);


This program can also complete the repeat operation and terminate the operation after 10 times, which differs from the setinterval () that it does not use the returned numeric ID.

Because SetInterval () is repeated execution, so there will always be a numeric ID return, so you have to keep track of this numeric ID, and settimeout () after the execution is no longer executed, so we do not have to track the return of the value ID, which gives us a certain convenience.

Also, the latter intermittent call may be invoked before the end of the previous intermittent call, which occurs when the function is executed longer than the intermittent call, so it is a good way to simulate the intermittent call with settimeout ().

Of course, in the relatively simple procedure with setinterval () or not a big problem (suddenly remembered a word, existence is reasonable ~ ~ ~ ~ ~).



SetTimeout () intermittent calls and setinterval () timeout calls

JavaScript is a single-threaded language, but it allows you to schedule code to execute at a specific time by setting a time-out value and intermittent time. The former executes code after a specified time, while the latter executes the code at a specified time.

The timeout call needs to use the settimeout () method of the Window object, and he accepts two parameters: the code to execute and the time in milliseconds. Where the first argument can be a string that contains JavaScript code, or it can be a function. For example, the following two calls to Sttimeout () will display a warning box after one second:

Passing strings is not recommended!  
settimeout ("alert (' Hello world! ')", 1000);  
//Recommended invocation mode
settimeout (function () {
alert ("Hello world!");
}, 1000);


Although neither of these calls is a problem, it is not recommended to use a string as the first argument because passing a string can result in performance loss. After calling SetTimeout (), the method returns a numeric ID that represents the timeout call. This timeout call ID is the unique identifier of the planned execution code that can be used to cancel the timeout call. To cancel a time-out call plan that has not yet been executed, you can call the Cleartimeout () method and pass the appropriate timeout call ID as a parameter, as follows:

Set Timeout call
var timeoutid = settimeout (function () {
alert ("Hello world!");  
}, 1000);
//Note: remove it
cleartimeout (Timeoutid);


The timeout call can be completely canceled as long as the cleartimeout () is invoked before the specified time has elapsed. The preceding code immediately invokes cleartimeout () after setting the timeout call, and the result is nothing like what happened.

An intermittent call is similar to a timeout call, except that it repeats the code at a specified interval until the intermittent call is canceled or the page is unloaded. The way to set up an intermittent call is setinterval (), which accepts the same arguments as settimeout (): The Code to execute (a string or function) and the number of milliseconds to wait before each execution. Here's an example:

Passing strings is not recommended!  
setinterval ("Alert (' Hello World ')", 10000);  
//Recommended invocation mode
setinterval (function () {
alert ("Hello world!");
}, 1000);


Calling the SetInterval () method also returns an intermittent call ID that can be used to cancel intermittent calls at some point in the future. To cancel an intermittent call that has not yet been performed, you can use the Clerarinterval () method and pass in the appropriate intermittent call ID. The importance of canceling intermittent calls is much higher than canceling the timeout call, because intermittent calls are performed to the page uninstall without interference. The following is a common example of using intermittent calls:

   var num = 0;       var max = 10;        var intervalId = null;               function incrementnumber ()  {            num++;           //If the number of executions reaches the value set by Max, To cancel subsequent calls that have not yet been executed            if  (Num == max)  {                clearinterval (intervalId);
               alert ("complete");           }       }        intervalid = setinterval (incrementnumber, 500);


        In this example, the variable num increments every half second, and when incremented to the maximum, the previously set intermittent call is canceled. This pattern can also be implemented using a time-out call, as follows:

    var num = 0;       var max =  10;              function incrementnumber ()  {           num++;            //if the number of executions does not reach the value set by Max, set another timeout call             if  (Num < max)  {                settimeout (incrementnumber, 500);            } else {                alert ("complete");           }        }       settimeout (incrementnumber, 500);


        visible, when using timeout calls, it is not necessary to trace the timeout call ID because each time the code is executed, the call stops itself if another timeout call is no longer set. It is generally thought that using time-out to simulate intermittent invocation is an optimal pattern. In the development environment, a real intermittent call is rarely used because the latter intermittent call may start before the end of the previous intermittent call. This can be avoided by using a time-out call as in the previous example. So it's best not to use intermittent calls.

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.