当前位置: 首页 > Web前端 > JavaScript

常见的前端手写功能

时间:2023-03-26 22:49:51 JavaScript

throttlefunctiondebounce(fn,delay){让定时器返回函数(...args){if(timer){clearTimeout(timer)}timer=setTimeout(()=>{fn.apply(this,args)},delay)}}//测试consttask=()=>{console.log('runtask')}constdebounceTask=debounce(task,1000)window.addEventListener('scroll',debounceTask)debouncefunctionthrottle(fn,delay){letlast=0//最后触发时间return(...args)=>{constnow=Date.now()if(now-last>delay){last=nowfn.apply(this,args)}}}//测试consttask=()=>{console.log('runtask')}constthrottleTask=throttle(task,1000)window.addEventListener('scroll',throttleTask)深拷贝函数deepClone(obj,cache=newWeakMap()){if(typeofobj!=='object')returnobj//普通类型,直接返回if(obj===null)returnobjif(cache.get(obj))returncache.get(obj)//防止循环引用,程序进入死循环if(objinstanceofDate)returnnewDate(obj)if(objinstanceofRegExp)returnnewRegExp(obj)//找到原型上的构造函数,原型上的构造函数指向当前对象的构造函数letcloneObj=newobj.constructor()cache.set(obj,cloneObj)//缓存复制的对象进行处理循环引用案例for(letkeyinobj){if(obj.hasOwnProperty(key)){cloneObj[key]=deepClone(obj[key],cache)//递归复制}}returncloneObj}//testconstobj={name:'Jack',address:{x:100,y:200}}obj.a=obj//循环引用constnewObj=deepClone(obj)console.log(newObj.address===obj.address)//false异步控制并发数functionlimitRequest(urls=[],limit=5){returnnewPromise((resolve,reject)=>{constlen=urls.lengthletcount=0//哪个任务是当前正在进行conststart=async()=>{consturl=urls.shift()//从数组中获取第一个任务if(url){try{awaitaxios.post(url)if(count==len-1){//最后一个任务resolve()}else{count++//成功,开始下一个ttaskstart()}}catch(e){count++//失败,同时开始下一个任务http://xxb','http://xxc','http://xxd','http://xxe'])