javascript's most basic function summary

  • 2020-06-19 09:49:17
  • OfStack

I remember in the early days of JavaScript, it was almost impossible to get anything done without a few simple functions, because browser providers implemented things differently, not just at the edges but also at the base, like addEventListener and attachEvent. Although times have changed, there are still a few functions that every developer should master in order to perform certain functions and improve performance.

debounce

For energy-intensive events, the debounce function is a good solution. If you don't use the debounce function for scroll, resize, and key* events, then you've almost made a mistake. The following debounce functions keep your code efficient:


//  return 1 If it is called continuously, it will not be executed. This function is called at stop  N  Milliseconds later, it is called again before it is executed. If there is a transmission   ' immediate'  Parameter, which immediately queues the function to execution 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 callback functions to execute more than one time. This function is particularly important when assigning a callback function to an event that frequently fires.

poll

Although I mentioned the debounce function above, if an event does not exist, you cannot insert an event to determine the desired state, and you need to check every once in a while to see if the state meets your requirements.


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 it doesn't run out of time, try again 1 time 
      else if (Number(new Date()) < endTime) {
        setTimeout(p, interval);
      }
      
//  If it does not match and takes too long, reject it! 
      else {
        errback(new Error('timed out for ' + fn + ': ' + arguments));
      }
  })();
}
 
//  Usage: Make sure the element is visible 
poll(
  function() {
    return document.getElementById('lightbox').offsetWidth > 0;
  },
  function() {
    
//  Execute, successful callback function 
  },
  function() {
    
//  Error, failed callback function 
  }
);

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

once

Sometimes you want a given feature to occur only once, similar to the onload event. The following code provides the functionality you say:


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 prevents duplicate initialization by ensuring that a given function can only be called once!

getAbsoluteUrl

Getting an absolute URL from a string variable is not as simple as you might think. For some URL constructors, it can be a problem if you don't provide the necessary parameters (and sometimes you really don't know what to provide). Here's an elegant trick where you just pass a string to get the corresponding absolute URL.


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

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

isNative

If you want to know if a specified function is native, or if you can override it declaratively. This easy-to-use piece of code will give you the answer:


;(function() {
 
 
//  Used to handle incoming parameters  value  The interior of the  `[[Class]]` 
 var toString = Object.prototype.toString;
 
 
//  Decompiled code to parse the function 
 var fnToString = Function.prototype.toString;
 
 
//  Used to detect host constructors   ( Safari > 4 ; Really output a specific array) 
 var reHostCtor = /^[object .+?Constructor]$/;
 
 
//  with 1 The standard native methods are compiled as templates 1 A regular expression. 
 
//  We choose  'Object#toString'  Because it 1 It won't be polluted. 
 var reNative = RegExp('^' +
  
//  will  'Object#toString'  Force to string  
  String(toString)
  
//  Escapes all specified regular expression characters 
  .replace(/[.*+?^${}()|[]/]/g, '$&')
  
//  with  '.*?'  Substitution referred to  'toString'  To keep the template universal. 
  
//  will  'for ...'  Such characters are replaced to be compatible  Rhino  , because these environments add additional information, such as the number of method parameters. 
  .replace(/toString|(function).*?(?=()| for .+?(?=])/g, '$1.*?') + '$'
 );
 
 function isNative(value) {
  var type = typeof value;
  return type == 'function'
   
//  with  'Function#toString'  ( fnToString ) bypasses the value ( value ) itself  'toString'  Method, so as not to be deceived by forgery. 
   ? reNative.test(fnToString.call(value))
   
//  Back to the host object check because some environments (browsers) will put an array of types ( typed arrays "(" As if  DOM  Method, which may not follow the standard native regular expression at this point. 
   : (value && type == 'object' && reHostCtor.test(toString.call(value))) || false;
 }
 
 
//  The export function 
 module.exports = isNative;
}());
 
//  usage 
isNative(alert); 
// true
isNative(myCustomFunction); 
// false

This function isn't perfect, but it does the job!

insertRule

We all know that you can get an NodeList through selectors (via document.querySelectorAll) and style each element, but what's a more efficient way to style selectors (for example, you can do this in a stylesheet) :


var sheet = (function() {
    
//  create  <style>  The label 
  var style = document.createElement('style');
 
    
//  If you need to specify the media type, you can add it here 1 a  media ( and / or  media query) 
  
// style.setAttribute('media', 'screen')
  
// style.setAttribute('media', 'only screen and (max-width : 1024px)')
 
  
// WebKit hack :(
  style.appendChild(document.createTextNode(''));
 
    
//  will  <style>  Elements are added to the page 
  document.head.appendChild(style);
 
  return style.sheet;
})();
 
//  usage 
sheet.insertRule("header { float: left; opacity: 0.8; }", 1);

This is especially useful for a site that is dynamic and heavily reliant on AJAX. If you style 1 selector, you don't need to style every element that matches (now or in the future).

matchesSelector
We often do input validation before the next step to make sure it is a reliable value, or that the form data is valid, etc. But how do we normally make sure that an element is qualified for the next step? If an element has a selector given a match, you can use the matchesSelector function to verify:


function matchesSelector(el, selector) {
  var p = Element.prototype;
  var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) {
    return [].indexOf.call(document.querySelectorAll(s), this) !== -1;
  };
  return f.call(el, selector);
}
 
//  usage 
matchesSelector(document.getElementById('myDiv'), 'div.someSelector[some-attribute=true]')

So there you have it, seven JavaScript functions that every developer should keep in mind all the time. What function did I miss? Please share it!

This is the end of this article, I hope you enjoy it.


Related articles: