Extended Javascript Function

Source: Internet
Author: User

Isn't the setTimeout method of the window object used? Bingo, that's right! If you often need to "execute a certain Function with latency" in an application, you can extend the global object of the Function Based on the DRY principle and add a delay method such as delay for the Function, this will make your code more concise and effective.
The method for adding delay to the expansion Function object is as follows:
Copy codeThe Code is as follows:
Function. prototype. delay = function (this1, timeout ){
This1 = this1 | null;
Timeout = timeout | 0;
Var _ this = this;
Var args = [];
// Obtain parameters. Note: 1st and 2nd parameters are reserved.
Switch (arguments. length ){
Case 1:
Timeout = parseInt (arguments [0]);
Timeout = isNaN (timeout )? 0: timeout;
Timeout = timeout <0? 0: timeout;
Break;
Default:
For (var I = 0; I <arguments. length; I ++ ){
If (I> 1) {args. push (arguments [I]) ;};
};
Break;
};
Var proxy = function (){
_ This. apply (this1, args );
};
Return window. setTimeout (proxy, timeout );
};

Test the code in the firebug plug-in console of firefox, for example:
Copy codeThe Code is as follows:
Var xx = function (n ){
This. name = n;
};
Xx. prototype. hi = function (a, B ){
Console. log (this. name + "-" + a + "-" + B );
};
Var xx1 = new xx ("levin ");
Var t = xx1.hi. delay (xx1, 1000, "cocoa", "yoyo ");
Xx1.hi ("guluglu", "jigujigu ");

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.