js基础扫盲 - 实现一个队列

简单的队列:

    function Queue() {
        this.list = []
    }
    Queue.prototype.setItem = function (item) {
        this.list.push(item)
    }
    Queue.prototype.getItem = function (count) {
        if (this.isEmpty()) {
            return {}
        }
        return this.list.splice(0, count)
    }
    Queue.prototype.isEmpty = function () {
        return this.list.length < 1
    }
    Queue.prototype.leftList = function () {
        return this.list
    }

    var q = new Queue()
    q.setItem({'name': '1'})
    q.setItem({'name': '2'})
    q.setItem({'name': '3'})


    console.log(q.leftList())

    var item = q.getItem(2)
    console.log(item)
    console.log(q.leftList())

添加定时获取红包的异步方法


    function Queue() {
        this.list = []
        this.count = 0
    }
    Queue.prototype.setItem = function (item) {
        this.list.push(item)
    }
    Queue.prototype.getItem = function (count) {
        if (this.isEmpty()) {
            return {}
        }
        return this.list.splice(0, count)
    }
    Queue.prototype.isEmpty = function () {
        return this.list.length < 1
    }
    Queue.prototype.leftList = function () {
        return this.list
    }
    Queue.prototype.startLoop = function () {
        var _this = this
        setTimeout(function () {
            _this.setItem({'name': _this.count})
            _this.count++
            _this.startLoop()
        }, 1000)
    }


    var q = new Queue()
    q.startLoop()


    setInterval(function () {
        console.log(q.getItem(2))
    }, 5000)

随机浏览