debounce function to prevent high frequency calls
This debounce function is essential for performing event-driven tasks to improve performance. If you are using scroll, resize, key* and other events to trigger the execution of tasks without using the reduced-frequency function, you have made a major mistake. The lower frequency function debounce will make your code more efficient:
Returns a function, which, as long as it continues to be invoked, would not//be triggered. The function would be called after it stops being called for//N milliseconds. If ' immediate ' is passed, trigger the function on the//leading edge, instead of the Trailing.function debounce (func, wait , immediate) {var Timeout;return function () {var context = this, args = Arguments;var later = function () {timeout = Null;i F (!immediate) func.apply (context, args);}; var callnow = immediate &&!timeout;cleartimeout (timeout); timeout = SetTimeout (later, wait); if (Callnow) Func.apply (context, args);};};/ /Usagevar MYEFFICIENTFN = debounce (function () {//All of the taxing stuff do}, Window.addeventlistener (' Resize ', my EFFICIENTFN);
This debounce function only allows the callback function you provide at a given time interval to execute once, reducing its frequency of execution. Such restrictions are especially important when encountering high-frequency triggering events.
set time/frequency cycle detection function
The Debounce function mentioned above is triggered by an event. But sometimes no such event is available, so we can only write a function on our own to check it every other time.
Function Poll (FN, callback, err, timeout, interval) {var startTime = (new Date ()). GetTime (); var pi = window.setinterval (function () {if (Math.floor ((new Date). GetTime ()-startTime)/+) <= timeout) { if (FN ()) {callback (); }} else {window.clearinterval (pi); Err (); }}, Interval)}
once functions that prohibit repeated calls and only allow execution once
Most of the time, we just want an action to be performed only once, as if we were using onload to restrict execution only once the load is complete. The following function will allow you to execute the operation once and then not repeat it.
Function once (FN, context) {var result;return function () {if (fn) {result = Fn.apply (Context | | this, arguments); fn = nul l;} return result;};} Usagevar canonlyfireonce = once (function () {console.log (' fired! ');}); Canonlyfireonce (); "Fired!" Canonlyfireonce (); Nada
This once function ensures that the function you provide only executes the only one time, preventing duplication of execution.
gets the absolute address of a link getabsoluteurl
Getting the absolute address of the link is not as simple as you might think. Here is a very useful function that can obtain an absolute address based on the relative address you enter:
var Getabsoluteurl = (function () {var a;return function (URL) {if (!a) a = document.createelement (' a '); a.href = Url;return A . href;};}) ();//Usagegetabsoluteurl ('/something '); Http://www.webhek.com/something
The A-tag href is used here to generate the complete absolute URL, which is very reliable.
determine if a JavaScript function is a system native function isnative
Many third-party JS scripts introduce new functions into global variables, some even overwrite the native functions of the system, and the following method is to check if they are native functions:
;(function () { //used to resolve the internal ' [[Class]] ' of values var toString = Object.prototype.toString; //used to resolve the decompiled source of functions var fntostring = Function.prototype.toString; //used to detect host constructors (Safari > 4; really typed array specific) var Rehostctor =/^\[o Bject. +? constructor\]$/; //Compile a regexp using a common native method as a template. //We chose ' object#tostring ' because there ' s a good chance it is not being mucked with. var renative = RegExp (' ^ ' + //coerce ' object#tostring ' to a string string (toString)   ; //Escape Any special regexp characters .replace (/[.*+?^${} () |[ \]\/\\]/g, ' \\$& ') //Replace mentions of ' toString ' with '. * "to keep the template generic. //Replace thing like ' for ... ' to support environments like Rhino which add extra info //such As metHod arity. .replace (/tostring| ( function). *? (? =\\\ () | for. +? (?=\\\]) /g, ' $1.*? ') + ' $ ' ); function isnative (value) { var type = typeof value; return type = = ' function '   ; //use ' function#tostring ' to bypass the value ' s own ' toString ' method //and avoid being Faked out. ? Renative.test (Fntostring.call (value)) //Fallback to a host object check because some environments wil L represent //things like typed arrays as DOM methods which could not conform to the &NBS p;//Normal native pattern. &NBSP;: (value && type = = ' object ' && rehostctor.test (Tostring.call (value))) | | False } //Export however you want module.exports = isnative;} ());//usageisnative (alert); Trueisnative (mycustomfunction); False
Although this method is not so concise, but still can complete the task!
Create a new CSS rule with JavaScript insertrule
Sometimes we use a CSS selector (such as Document.queryselectorall) to get a NodeList, and then give each of them a style in turn. In fact, this is not an efficient approach, and it is efficient to create a new CSS style rule with javascript:
Build a better Sheet object Sheet = (function () {//Build Stylevar style = document.createelement (' style '); Style.setatt Ribute (' media ', ' screen '); Style.appendchild (document.createTextNode ("));d Ocument.head.appendChild (style);// Build and return a single functionreturn function (rule) {style.sheet.insertRule (rule, style.sheet.cssRules.length);};} ) ();/Then call as a Functionsheet (". stats {position:relative; top:0px} ");
These practices are very efficient, and in some scenarios, such as using AJAX to load a new piece of HTML, you do not need to manipulate the newly loaded HTML content.
determine if a page element has a property and style Matchesselector
function Matchesselector (el, selector) {var p = element.prototype;var f = p.matches | | p.webkitmatchesselector | | p.mozmat Chesselector | | P.msmatchesselector | | function (s) {return [].indexof.call (Document.queryselectorall (s), this)!==-1;}; Return F.call (el, selector);} Usagematchesselector (document.getElementById (' mydiv '), ' div.someselector[some-attribute=true] ')
This is the 7 JavaScript functions, and each Web programmer should know how to use them. You can write other functions that you think are necessary in the comments and share them, thank you.
7 JavaScript functions required by web developers