多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### 函数分时加载:间隔200ms执行一次渲染函数 ``` let arr = [] for(let i = 0; i < 1000; i++) { arr.push(i) } function timeout(arg, fn, count) { var timer, data; function start() { for(let i = 0; i < Math.min( count || arg.length ); i++) { data = arg.shift() fn(data) } } return function() { timer = setInterval(function() { console.log('in') if (!arg.length) { return clearInterval(timer) } start() }, 200) } } let render = timeout(arr, function(data) { let div = document.createElement('div') div.innerHTML = data document.body.appendChild( div ) }, 8) render() ``` ### 函数节流:500ms执行一次onmouse事件 ``` let div = document.querySelector('div') function water(fn, delay) { var timer, firstTime = true, _fn = fn; return function() { const _this = this const arg = arguments; if (firstTime) { _fn.apply(_this, arg) return firstTime = false; } if (timer) { return false } timer = setTimeout(function() { clearTimeout(timer) timer = null _fn.apply(_this, arg) }, delay || 500) } } div.onmousemove = water(function() { console.log('1') }, 500) ``` ### 1. 单例模式 ``` function Single(name) { this.name = name this.instance = null } Single.prototype = { constructor: Single, getInstance(name) { if (!this.instance) { this.instance = new Single(name) } return this.instance } } const obj = Single.prototype.getInstance('Jack') const obj2 = Single.prototype.getInstance() console.log(obj.name) console.log(obj2.name) ``` ### 惰性单例 ``` let div = document.querySelector('div') function createDom() { let instance = null; return function() { if (!instance) { instance = document.createElement('div') instance.style.width = '300px' instance.style.height = '300px' instance.style.background = 'skyblue' instance.style.display = 'none' document.body.appendChild( instance ) } console.log(instance, 'test') return instance }() } div.onclick = function() { let dom = createDom() dom.style.display = 'block' } ```