美文网首页
有用代码段

有用代码段

作者: TOPro | 来源:发表于2018-03-28 09:08 被阅读13次

    简书不能发布隐藏文章吗?,公开就公开了吧

    
    
    {
        //  -------------------------------------------------------------
        //生成上下150年的年份列表
        yearList:
        new Array(150+1).fill(0).map((e,i,a)=>new Date().getFullYear()-((a.length/2)>>0)+i+"年"),
    
        //  -------------------------------------------------------------
        //生成月份列表
        monthList:new Array(12).fill(0).map((e,i)=>i+1+"月")
        /**
         *  -------------------------------------------------------------
         * 错误信息提取
         * @param err
         * @returns {*|string|string}
         */
          trimErrorMessage(err){
            if(!err) {
                return "未知错误"
            }
            if(err.data) {
                err = err.data;
                try{
                    err = JSON.parse(err);
                }catch(e){/*console.log();*/}
            }
            var text = ""
                || err.error        || err.errorText
                || err.message      || err.msg
                || err.statusText   || err
            ;
            return text;
        },
    
    
        /**
         * 描述太难,看例子
         * let retryAjax = retry({times:10,duration:1000});
         * retryAjax($.get,["/user",{id:1053256}])
         *      .then(resp={
         *          //10次内,有一次成功就会进入成功
         *      })
         *      .catch(resp=>{
         *          //重试10次,显示第10次的错误
         *      })
         * ;
         * @param genOptions
         * @returns {Function}
         */
        retry(genOptions){
            const defaultOptions = {
                scope:null,
                times:5,
                duration:1000,
                retryCallback(error, times){}
            }
    
            /**
             * function(thenable,options)
             * function(thenable,options,args)
             * function(thenable,args)
             */
            return function(thenable,options,args){
                if(Array.isArray(options)) {
                    args = options;
                    options = undefined;
                }
                options = Object.assign({},defaultOptions,genOptions,options);
                let counter = 0;
                return new Promise((resolve,reject)=>{
                    function retry(){
                        thenable.apply(options.scope,args||[])
                            .then(resolve)
                            .catch(resp=>{
                                counter++;
                                options.retryCallback(resp,counter);
                                if(counter<options.times) {
                                    setTimeout(retry,options.duration)
                                }else{
                                    reject(resp)
                                }
                            })
                        ;
                    }
                    retry();
                })
            }
        },
    
    
    
        /**
         * -------------------------------------------------------------
         * 重复执行stepHandler,达成这3中条件为止,结束重复
         *      1. !!stepHandler()==true
         *      2. times>0时,times表示重复执行最大时间毫秒数,时间耗尽停止重复
         *      3. times<0,times表示重复执行的最大次数,次数耗尽停止
         * @param interval  重复执行setp的间隔,默认90ms
         * @param times     重复执行最大次数的定义,避免一直重复下去
         *        times>0   表示重复执行多久时间。单位毫秒
         *        times<0   表示重复执最大多少次,单位 次
         * @param stepHandler      被重复执行的函数,如果该函数返回true停止重复
         *        function(flag){} //flag如果flag为true,
         *        表示为重复执行时间已经到,或者重复执行的次数已到
         */
        runUntil(interval,times,stepHandler){
            var time_mode = false;
            if(typeof interval == "function") {
                times = 0;
                stepHandler = interval;
                interval = 90;
            }else if(typeof interval == "number" && typeof times == "function"){
                stepHandler = times;
                times = 0;
            }
            var interval = setInterval(function () {
                if(stepHandler()){
                    clearInterval(interval);
                }
                if(judge()){
                    clearInterval(interval);
                    stepHandler(true);
                }
            }, interval);
            var now = new Date().getTime();
            function judge(){
                if(times<0){
                    times ++ ;
                    if(times === 0){
                        return true;
                    }
                }else if(times>0){
                    if(new Date().getTime() - now > times ){
                        return true;
                    }
                }
            }
        }
    
    
        
        
        //-------------------------------------------------------------
        // 独立的除抖函数
        // 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.
        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);
            };
        },
       
        //-------------------------------------------------------------
        // 独立的节流函数
        // Returns a function, that, when invoked, will only be triggered at most once
        // during a given window of time. Normally, the throttled function will run
        // as much as it can, without ever going more than once per `wait` duration;
        // but if you'd like to disable the execution on the leading edge, pass
        // `{leading: false}`. To disable execution on the trailing edge, ditto.
        throttle(func, wait, options) {
            var context, args, result;
            var timeout = null;
            var previous = 0;
            if (!options) options = {};
            var later = function() {
                previous = options.leading === false ? 0 : Date.now();
                timeout = null;
                result = func.apply(context, args);
                if (!timeout) context = args = null;
            };
            return function() {
                var now = Date.now();
                if (!previous && options.leading === false) previous = now;
                var remaining = wait - (now - previous);
                context = this;
                args = arguments;
                if (remaining <= 0 || remaining > wait) {
                    if (timeout) {
                        clearTimeout(timeout);
                        timeout = null;
                    }
                    previous = now;
                    result = func.apply(context, args);
                    if (!timeout) context = args = null;
                } else if (!timeout && options.trailing !== false) {
                    timeout = setTimeout(later, remaining);
                }
                return result;
            };
        },
    
    
    
    }
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:有用代码段

          本文链接:https://www.haomeiwen.com/subject/dgtycftx.html