Javascript learning notes-timer

Source: Internet
Author: User

Javascript learning notes-timer
Introduction

JavaScript provides the function of regularly executing code, called the timer, which is mainly completed by the setTimeout () and setInterval () functions.

TimeoutsetTimeout: specifies the number of milliseconds after which a function or code segment executes the Syntax: var timerId = setTimeout (func | code, delay) parameter.
Javascript statement string or function: Code interval to be executed (MS): indicates the number of milliseconds since the current time when the first parameter return value is executed: an integer representing the timer number, it can be used to cancel the timer later

Instance

// Javascript statement string setTimeout ("alert ('5 seconds! ') ", 5000); // function setTimeout (function () {alert ('5 seconds! ');}, 5000)
ClearTimeout: cancels a specified scheduled task. tasks that have been started cannot be canceled (?) Parameter: scheduled event id, that is, the returned value after setTimeout execution: undefined

Instance:

var timedTaskId = setTimeout("alert('5 seconds!')", 5000);clearTimeout(timedTaskId);
IntervalsetInterval function: Call the function or compute expression syntax according to the specified period (in milliseconds): setInterval (code, millisec [, "lang"]) parameter
Code: required. The function to be called or the code string to be executed millisec: required. The time interval between periodic execution or call code. The return value is in milliseconds. One can be passed to Window. clearInterval () cancels the periodically executed value of the code

Example:

// Javascript statement string setInterval ("alert ('5 seconds! ') ", 5000); // function setInterval (function () {alert ('5 seconds! ');}, 5000)
ClearInterval: cancels the scheduled task syntax set by setInterval (): clearInterval (id_of_setinterval) parameter.
Id_of_setinterval: Return Value of ID returned by setInterval (): undefined

Example

var timedTaskId = setInterval("alert('5 seconds!')", 5000);clearInterval(timedTaskId);
Operating Mechanism

Refer to the timer running mechanism in the JavaScript Standard Reference tutorial

FAQ: scheduled tasks with cyclic calls

You can call setTimeout repeatedly by creating a function loop to implement functions similar to setInterval, as shown in the following example:

function showTime() {    var today = new Date();    alert( " The time is: " + today.toString());    setTimeout( " showTime() " , 5000 );}showTime();

The code implementation function shown above can be implemented using setInterval as follows:

function showTime() {    var today = new Date();    alert( " The time is: " + today.toString());}setInterval("showTime()", 5000);

Reprinted: the two methods may look very similar and the displayed results will be very similar. However, the biggest difference between the two is that the setTimeout method does not execute the showTime function every five seconds, it executes the showTime function five seconds after each setTimeout call. This means that if the main part of the showTime function needs to be executed in 2 seconds, the whole function will be executed every 7 seconds. While setInterval is not bound by the function called by itself, it simply repeats the function at a certain time. If you want to execute an action accurately after a fixed interval, you 'd better use setInterval. If you don't want to interfere with each other due to continuous calls, in particular, each function call requires heavy computing and a long processing time, so it is best to use setTimeout

You can add more parameters after the second parameter to setTimeout of the callback function. These parameters are used as parameters for callback function calling in turn, but IE9.0 and earlier versions are not supported. Example:
Function add (a, B ){
Console. log (a + B );
}
SetTimeout (add, 1000, 1, 1); an anonymous function calls the callback function to pass parameters. Example:
Function add (a, B ){
Console. log (a + B );
}
SetTimeout (function (){
Add (1, 1 );
}, 1000); bind the redundant parameters to the callback function, and generate a new function into setTimeout. Example:
Function add (a, B ){
Console. log (a + B );
}
SetTimeout (add. bind (null, 1, 1), 1000); custom setTimeout, use the apply method to call back the parameter input

Note: The parameter issue of The setInterval callback function is the same as that of setTimeout.

Scope of callback Functions

The default callback function of the timer points to the global environment during execution, rather than defining the object of the callback function. Solution:
1. The anonymous function is called using the callback function's owner object, or the apply function is used to modify the scope.
2. Use the bind method to bind the scope of the callback function to the specified object.

Cancel all scheduled tasks

The setTimeout and setInterval functions return an integer that represents the counter number. When the integer is passed into the clearTimeout and clearInterval functions, the corresponding timer can be canceled. The integer returned by setTimeout and setInterval is continuous. That is to say, the integer returned by the second setTimeout method is 1 greater than the first integer. You can write a function to cancel all current settimeouts. Example:

(function() {  var gid = setInterval(clearAllTimeouts, 0);  function clearAllTimeouts() {    var id = setTimeout(function() {}, 0);    while (id > 0) {      if (id !== gid) {        clearTimeout(id);      }      id--;    }  }})();

Note: This section is taken from the JavaScript Standard Reference tutorial-timer

SetTimeout (f, 0)

By learning the timer running mechanism, we can know that f will not be executed immediately. It must wait until the synchronization tasks of the current script and the existing events in the "task queue" are all processed,. For more information, see the JavaScript Standard Reference tutorial-setTimeout (f, 0) of the timer.

Maximum time interval

32-bit number. If the value exceeds the upper limit, the value is overflow. The value 0 is used directly.

Application input box anti-Jitter

Refer to JavaScript Standard Reference tutorial-timer clearTimeout practical application

SetTimeout (f, 0)

According to the setTimeout (f, 0) feature, it has many application scenarios. For more information, see the JavaScript Standard Reference tutorial-setTimeout (f, 0) application of the timer.

Reference w3school-JavaScript timing w3school-HTML DOM setInterval () method w3school-HTML DOM clearInterval () method Ruan Yifeng-timer

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.