setTimeout模拟interval

 /**
     * @param fn: {Function}      // function which to execute
     * @param timer: {number}     // gap time between handle
     * @param count: {number}     // count of execute
     * **/
    function Interval(fn, timer, count) {
        var interval = function() {
            if (typeof count === 'undefined' || count-- > 0) {
                setTimeout(interval, timer);
                try {
                    fn.call(null);
                } catch(e) {
                    count = 0;
                    throw e;
                }
            }
        };
        setTimeout(interval, timer);
    }

    Interval(function() {
        console.log(1);
    }, 1000, 5);

 

posted @ 2017-12-29 00:13  井凉一一  阅读(159)  评论(0编辑  收藏  举报