Javascript: the most basic function aggregation _ javascript skills

Source: Internet
Author: User
This article provides a summary of the seven most basic functions of javascript, which are very practical. For more information, see. I remember that in the early days of JavaScript, there were almost no simple functions to accomplish anything, Because browser providers had different implementation functions, not only edge functions, but also basic functions, such as addEventListener and attachEvent. Although the times have changed, there are still some functions that every developer should master in order to complete some functions and improve performance.

Debounce

For highly energy-consuming events, the debounce function is a good solution. If you do not use the debounce function for scroll, resize, and key * events, you are almost equivalent to making an error. The following debounce function keeps your code efficient:

// Return a function. If it is continuously called, it will not be executed. This function can be executed only after it is called again N milliseconds after it is stopped. If the 'immediate' parameter is passed, the function will be immediately arranged in the execution queue without delay. Function debounce (func, wait, immediate) {var timeout; return function () {var context = this, args = arguments; var later = function () {timeout = null; if (! Immediate) func. apply (context, args) ;}; var callNow = immediate &&! Timeout; clearTimeout (timeout); timeout = setTimeout (later, wait); if (callNow) func. apply (context, args) ;};}; // usage var myEfficientFn = debounce (function () {// all heavy operations }, 250); window. addEventListener ('resize', myEfficientFn );

The debounce function does not allow the callback function to be executed more than once within the specified time. This function is especially important when a callback function is assigned for an event that is frequently triggered.

Poll

Although I mentioned the debounce function above, if an event does not exist, you cannot insert an event to determine the desired state, check whether the status meets your requirements at intervals.

Function poll (fn, callback, errback, timeout, interval) {var endTime = Number (new Date () + (timeout | 2000); interval = interval | 100; (function p () {// if the condition is met, execute! If (fn () {callback () ;}// if the condition is not met but does not time out, then else if (Number (new Date () <endTime) {setTimeout (p, interval);} // The request is rejected if it does not match and the time consumption is too long! Else {errback (new Error ('timed out for '+ fn +': '+ arguments) ;}) () ;}// usage: make sure that the element is visible to poll (function () {return document. getElementById ('lightbox '). offsetWidth> 0 ;}, function () {// execution, successful callback function}, function () {// error, failed callback function });

Polling has been applied in the web for a long time and will be used in the future.

Once

Sometimes you want a given function to happen only once, similar to an onload event. The following code provides the functions you mentioned:

Function once (fn, context) {var result; return function () {if (fn) {result = fn. apply (context | this, arguments); fn = null;} return result ;};}// usage var canOnlyFireOnce = once (function () {console. log ('fired! ') ;}); CanOnlyFireOnce (); // "Fired! "CanOnlyFireOnce (); // nada // The specified function is not executed

The once function ensures that a given function can be called only once to prevent repeated initialization!

GetAbsoluteUrl

Getting an absolute URL from a string variable is not as simple as you think. For some URL constructors, problems may occur if you do not provide necessary parameters (and sometimes you do not know what parameters are provided ). Here is an elegant technique. You only need to pass a string to get the corresponding absolute URL.

Var getAbsoluteUrl = (function () {var a; return function (url) {if (! A) a = document. createElement ('A');. href = url; return. href; };}) (); // usage getAbsoluteUrl ('/something'); // http://davidwalsh.name/something

Element a's href processing and url Processing seem meaningless, while the return statement returns a reliable absolute URL.

IsNative

If you want to know whether a specified function is native or whether it can be overwritten by declaration. The following easy-to-use code gives you the answer:

; (Function () {// It is used to process the internal '[[Class]' var toString = Object. prototype. toString; // The decompilation code used to parse the Function var fnToString = Function. prototype. toString; // used to detect the host Constructor (Safari> 4; actually outputs a specific array) var reHostCtor =/^ [object. +? Constructor] $ // use a standard native method as a template to compile a regular expression. // Select 'object # tostring' because it will not be contaminated. Var reNative = RegExp ('^' + // convert 'object # tostring' to a String (toString) // escape all specified Regular Expression characters. replace (/[. * +? ^ $ {} () | []/G, '$ &') // use '.*? 'Replace the mentioned 'tostring' to ensure the versatility of the template. // Replace characters such as 'for...' to be compatible with environments such as Rhino, because additional information, such as the number of method parameters, is added to these environments.. Replace (/toString | (function ).*? (? = () | For. +? (? =])/G, '$1 .*? ') +' $ '); Function isNative (value) {var type = typeof value; return type = 'function' // use 'function # tostring' (fnToString) the 'tostring' method of value itself is bypassed to avoid spoofing.? ReNative. test (fnToString. call (value) // roll back to the check of the Host object, because some environments (browsers) treat things like the type array (typed arrays) as DOM methods, in this case, the standard native regular expression may not be followed.: (Value & type = 'object' & reHostCtor. test (toString. call (value) | false;} // export the function module. exports = isNative;} (); // use isNative (alert); // trueisNative (myCustomFunction); // false

This function is not perfect, but it can complete the task!

InsertRule

We all know that the selector (via document. querySelectorAll) Get a NodeList and set a style for each element, but what is a more efficient way to set a style for the selector (for example, you can do it in the style sheet ):

Var sheet = (function () {// create
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.