tools.js 1.31 KB
function trimSpace(str) {
    return str.replace(/\s+/g, '');
}
// trimSpace(str).length < = 0弹出提示

function throttle (fn, delay) {
    var t = null,
        begin = new Date().getTime();

    return function () {
        var _self = this,
            args = arguments,
            cur = new Date().getTime();

        clearTimeout(t);

        if(cur - begin >= delay) {
            fn.apply(_self, args);
            begin = cur;
        } else {
            t = setTimeout(function () {
                fn.apply(_self, args);
            }, delay);
        }
    }
}

function debounce(fn, delay, triggerNow) {
    var t = null;

    var debounced =  function(){
        var _self = this,
            args = arguments;
        if(t){
            clearTimeout(t);
        }
        if(triggerNow){
            var exec = !t;
            
            t = setTimeout(function(){
                t = null;
            }, delay);

            if(exec){
                // 初次进来
                fn.apply(_self, args);
            }
        }else{
            t = setTimeout(function(){
                fn.apply(_self, args);
            }, delay);
        }
    }

    debounced.remove = function(){
        clearTimeout(t);
        t = null;
    }

    return debounced;
}

export {
    trimSpace,
    throttle,
    debounce
}