首页 > 如何实现一个方法在30秒内只能调用一次(按上次调用时间开始),

如何实现一个方法在30秒内只能调用一次(按上次调用时间开始),

1,如题有多少种方法 ?2,是否可以封装成一个公用的方法? 大家有什么例子一起交流下啊~


一般的解决方法就是使用闭包,上面老师的解答都是这个思路,我认为挺好的。如果要使用公共的方法,也很简单,将方法挂到window下即可,如下:

(function(){
    let last
   window.dont30second=function(func, duration) {
         let now = Date.now()
         if (last && (now - last) < duration / 1e3) return
        last = now
        func.apply(this, arguments)
    }
 })();

var method = (function () {
    var wait = 0,
    t,
    timer = function () {
        wait = 30;
        t = setInterval(function () {
                if (wait) {
                    wait--;
                } else {
                    clearInterval(t);
                }
            }, 1000);
    }
    return function () {
        if (wait === 0) {
            //do something
            timer();
        } else {
            alert('技能冷却中,还需' + wait + '秒。');
        }
    }
})();

临时写的,没有测试过,不知道有没有效果。

改成下面这种,算不算封装?

/*
options = {
    wait : 30,
    onResolved : function(){},
    onRejected : function(){}
}
*/

var define = function (options) {
    options = typeof options === 'object' ? options : {};

    return (function () {
        var wait = 0,
        t,
        timer = function () {
            wait = ((typeof options.wait === 'number') && (options.wait >= 0)) ? options.wait : 30;
            t = setInterval(function () {
                    if (wait) {
                        wait--;
                    } else {
                        clearInterval(t);
                    }
                }, 1000);
        }
        return function () {
            if (wait === 0) {
                (typeof options.onResolved === 'function') && options.onResolved();
                timer();
            } else {
                (typeof options.onRejected === 'function') && options.onRejected();
            }
        }
    })();
}

function throttle (func, duration) {
    // duration 以秒计
    let last
    return function () {
         let now = Date.now()
         if (last && (now - last) < duration * 1e3) return
        last = now
        func.apply(this, arguments)
    }
}

手机码字

【热门文章】
【热门文章】