The solution of SetInterval and settimeout cannot pass function with parameters in JS

Source: Internet
Author: User

In JS, whether it is settimeout or setinterval, when using the function name as the call handle can not take parameters, and in many cases must take parameters, and then to introduce specific solutions

In JS, either settimeout or setinterval, you cannot take arguments with the function name as the invocation handle, and in many cases you have to take parameters.
This needs to be solved in a way.
One, the use of string form:--(defect) parameters can not be changed periodically
SetInterval ("foo (ID)", 1000);
Second, anonymous function packaging (recommended)

Window.setinterval (function

The function of foo (ID) can be executed periodically, and the variable ID is passed in.
Iii. defining functions that return no parameter functions

functionfunctionreturnfunction() {foo (id);}} Window.setinterval (_foo (ID),

This defines a function _foo, which receives a parameter and returns a function with no parameters, using the parameters of the external function inside the function to invoke it without using parameters.
In window. setinterval function, the function of parameter passing is realized by using _foo (ID) to return a function handle without parameters.
Iv. Modification of SetInterval

functionvar _sto =functionvar args = Array.prototype.slice.call (arguments,2varfunction() {callback.apply (  Null, args); } _sto (_cb,timeout); } window.setinterval (Hello,

All of the above methods are also suitable for settimeout.

The solution of SetInterval and settimeout cannot pass function with parameters in JS

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.