Javascript practice-function object extension-delayed execution function

Source: Internet
Author: User

After arriving at Sohu, I was busy. I haven't written essays in the garden for a long time ~~

This article mainly introduces "how to execute a function at a delay in JS ?"

Isn't the setTimeout method of the window object used? Bingo, that's right! If youThe application often needs to "delay the execution of a certain function"Then, based on the dry principle, you can expand the global objects of the function, and add a delay method such as delay for the function, which will make your code more concise and effective.

The method for adding delay to the expansion function object is as follows:

Code

 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:

Code

 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.