关键词:
// debounce
// The debounce function can be a game-changer when it comes to event-fueled performance.
// If you aren't using a debouncing function with a scroll, resize, key* event, you're probably doing it wrong.
// Here's a debounce function to keep your code efficient:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will 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;
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 the taxing stuff you do
, 250);
window.addEventListener('resize', myEfficientFn);
The debounce function will not allow a callback to be used more than once per given time frame. This is especially important when assigning a callback function to frequently-firing events.
// poll
// As I mentioned with the debounce function,
// sometimes you don't get to plug into an event to signify a desired state --
// if the event doesn't exist, you need to check for your desired state at intervals:
// The polling function
function poll(fn, timeout, interval)
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
var checkCondition = function(resolve, reject)
// If the condition is met, we're done!
var result = fn();
if(result)
resolve(result);
// If the condition isn't met but the timeout hasn't elapsed, go again
else if (Number(new Date()) < endTime)
setTimeout(checkCondition, interval, resolve, reject);
// Didn't match and too much time, reject!
else
reject(new Error('timed out for ' + fn + ': ' + arguments));
;
return new Promise(checkCondition);
// Usage: ensure element is visible
poll(function()
return document.getElementById('lightbox').offsetWidth > 0;
, 2000, 150).then(function()
// Polling done, now do something else!
).catch(function()
// Polling timed out, handle the error!
);
// once
// There are times when you prefer a given functionality only happen once,
// similar to the way you'd use an onload event. This code provides you said functionality:
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
// getAbsoluteUrl
// Getting an absolute URL from a variable string isn't as easy as you think.
// There's the URL constructor but it can act up if you don't provide the required arguments
// (which sometimes you can't). Here's a suave trick for getting an absolute URL from and string input:
var getAbsoluteUrl = (function()
var a;
return function(url)
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
;
)();
// Usage
getAbsoluteUrl('/something'); // https://davidwalsh.name/something
// isNative
// Knowing if a given function is native or not can signal if you're willing to override it.
// This handy code can give you the answer:
;(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 = /^\[object .+?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 will represent
// things like typed arrays as DOM methods which may not conform to the
// normal native pattern.
: (value && type == 'object' && reHostCtor.test(toString.call(value))) || false;
// export however you want
module.exports = isNative;
());
// Usage
isNative(alert); // true
isNative(myCustomFunction); // false
// The function isn't pretty but it gets the job done!
// insertRule
// We all know that we can grab a NodeList from a selector (via document.querySelectorAll)
// and give each of them a style, but what's more efficient is setting that style to a selector
// (like you do in a stylesheet):
var sheet = (function()
// Create the <style> tag
var style = document.createElement('style');
// Add a media (and/or media query) here if you'd like!
// style.setAttribute('media', 'screen')
// style.setAttribute('media', 'only screen and (max-width : 1024px)')
// WebKit hack :(
style.appendChild(document.createTextNode(''));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
)();
// Usage
sheet.insertRule("header float: left; opacity: 0.8; ", 1);
// This is especially useful when working on a dynamic,
// AJAX-heavy site. If you set the style to a selector, you don't need to account
// for styling each element that may match that selector (now or in the future).
// matchesSelector
// Oftentimes we validate input before moving forward; ensuring a truthy value,
// ensuring forms data is valid, etc. But how often do we ensure an element qualifies
// for moving forward? You can use a matchesSelector function to validate if an element
// is of a given selector match:
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]')
泛函是个什么概念
...,举个简单一点的列子,我们以前学的函数是把数字作为基本的元素来研究的,现在更高一个层次,就是元素就是一个函数,比如全体实系数连续函数构成一个集合A,那么这个A中每一个元素就是一个函数,而泛函就是研究在类... 查看详情
javascript中大括号“{}”的多义性
摘要:本文主要介绍JavaScript中大括号有四种语义作用。 JS中大括号有四种语义作用 语义1,组织复合语句,这是最常见的if(condition){//...}else{//...}for(){//...} 语义2,对象直接量声明varobj={ name:‘jack‘, age:23}; 整个是个... 查看详情
javascript基本包装类型
基本包装类js中为了便于基本类型操作,提供了3个特殊的引用类型:Boolean、Number、String它们具有基本类型特殊行为。实际上,每当读取一个基本类型的时候,js内部会自动创建一个基本包装类型对象,可以让我们调用一些方法来... 查看详情
javascript基本包装类介绍
为了便于操作基本类型值,ECMAScript提供了3个特殊的引用类型:Boolean、Number和String。这些类型与其他引用类型相似,但同时也具有与各自的基本类型相应的特殊行为。实际上,每当读取一个基本类型值的时候,后台就会创建... 查看详情
javascript编程风格--基本的格式化
缩进层级 推荐4个空格字符作为一个缩进层级。语句结尾 推荐不要省略分号。行的长度 最好一行不超过80个字符。换行 在运算符后换行,下一行增加两个层级的缩进。 例外:给变量... 查看详情
基本的javascript概念理解[重复]
这个问题在这里已有答案:
Howdoesthe“this”keywordwork?23回答
Howtoaccessthecorrect`this`insideacallback?10个答案
我试图了解各种javascript概念,而我无法理解的一件事就是为什么这样做:varcounterObject={counter:0,start: 查看详情
javascript基本包装类型及其操作方法
1.为了便于操作基本类型值,ECMAScript还提供了3个特殊的因哟用类型:Boolean、Number、Striung。这些类型与其他引用类型相似,但同时也具有各自的基本类型相应的特殊行为,实际上每当读取一个基本类型值得时候,后台就会创建一... 查看详情
javascript中基本类型和引用类型的区别分析
...之一就是值类型和引用类型的区别。下面我们来看一下在JavaScript中基本数据类型(PrimitiveTypes)和引用类型(ReferenceTypes)的区别。、基本类型和引用类型ECMAScript包含两个不同类型的值:基本类型值和引用类型值。基本类型值指的... 查看详情
我想创建一个基本的 Javascript 滑块
】我想创建一个基本的Javascript滑块【英文标题】:IwanttocreateaBasicJavascriptslider【发布时间】:2013-07-1812:50:11【问题描述】:我的网站需要一个基本的图片滑块,由五张图片组成,顺序如下开始时>第一张应该可见3秒然后消失图... 查看详情
c标准函式库的历史沿革
参考技术A1995年,NormativeAddendum1(NA1)批准了三个表头档(iso646.h,wchar.h,andwctype.h)增加到C标准函式库中。C99标准增加了六个表头档(complex.h,fenv.h,inttypes.h,stdbool.h,stdint.h,andtgmath.h)。C11标准中又新增了5个表头档(stdalign.h,stdatomic.h,stdnoreturn.... 查看详情
javascript高级编程笔记01(基本概念)
1、在html中使用JavaScript 1、 <script>元素 <script>定义了下列6个属性: async:可选,异步下载外部脚本文件。 charset:可选,通过src属性指定代码的字符集,大多浏览器会忽略这... 查看详情
javascriptdom基本使用
JavaScript的基本语法就不赘述了,直接看Dom的相关例子。Dom的原生使用不是太多,一般情况下使用JQuery更加简单,不过Dom的基本方法还是需要了解一下的。例1请输入关键字栏目javascript是默认的脚本语言,因此type=‘text/javascript可... 查看详情
javascript----基于对象的操作
常用对象为了便于操作基本类型值,ECMAScript提供了3个特殊的引用类型:Boolean,Number,String。它们是引用类型。当读取基本数据类型时,后台就会创建一个对应的基本包装类对象,所以我们在操作基本数据类型时,可以直接调用一... 查看详情
用pyton回答请输入3个小数,用print()函输出3个数,数之间用逗号分隔?
...的方式大概就是这样了参考技术A回答用pyton回答请输入3个小数,用print()函输出3个数,数之间用逗号分隔?您好亲,在Python语言中,实现数据的输出是使用print函数;(1)print函数print函数可以打印输出数据的输出操作,其语法结构如... 查看详情
javascript正则表达式模式匹配——基本字符匹配
1varpattern=/g..gle/;//点符号表示匹配除了换行符外的任意字符2varstr=‘g78gle‘;3alert(pattern.test(str));456varpattern=/go*gle/;//o*,表示0个或者多个o7varstr=‘goooooooooooogle‘;8alert(pattern.test(str));910varpattern=/go+gle/;//o 查看详情
JavaScript 三元运算符可以支持 3 个条件吗?
】JavaScript三元运算符可以支持3个条件吗?【英文标题】:CanaJavaScriptternaryoperatorsupport3conditions?【发布时间】:2018-03-1319:42:11【问题描述】:鉴于以下JavaScript三元运算符,是否可以使其支持3个条件而不是当前的两个条件?constcol... 查看详情
《非线性泛函分析导论:拓扑方法导论》
...法导论这一节详细讨论拓扑方法。其中 Brouwe拓扑度的基本使用方法在之前介绍流形的环绕时我们已经接触过。Brouwer度是拓扑学中的重要工具,但对于泛函分析而言,我们需要将其延伸至无限维空间。这就是Leray-Schaulder拓扑... 查看详情
2015年最棒的10个javascript框架
JavaScript是最流行的前端开发程序设计语言。它为WEB开发者提供了能够设计出具有丰富功能、干净用户界面的WEB应用的能力。JavaScript框架使得WEB应用的设计变的简单,并且它能够提供很多的功能和方法。有非常非常多的JavaScript框... 查看详情