• Đăng ký
  • Đăng nhập

Queue trong Javascript (Hàng đợi trong javascript)

📅 — 👀 856 — 👦

Trang này có hữu ích không?

👍 Có (13)        👎 Không (17)


Trong blogspot, khi chúng ta cần load nhiều Label trên website hay cần thực thi nhiều hàm javascript thì tôi khuyên bạn nên dùng Queue (hàng đợi). Queue hoạt động như sau, ta cần load 10 hàm javascript thì sẽ lần lượt đưa 10 hàm javascript vào Queue (hàng đợi), sau đó sẽ thực hiện từng hàm 1, khi hàm được thực hiện xong thì mới gọi hàm sau thực hiện. Với cách này thì 1 lần sẽ load lần lược từng hàm chứ không load 1 lần 10 hàm, tránh làm chậm website.

 Sau đây là code để thực hiện :


var Queue = (function () {





    Queue.prototype.autorun = true;


    Queue.prototype.running = false;


    Queue.prototype.queue = [];




    function Queue(autorun) {


        if (typeof autorun !== "undefined") {


            this.autorun = autorun;


        }


        this.queue = []; //initialize the queue


    };




    Queue.prototype.add = function (callback) {


        var _this = this;


        //add callback to the queue


        this.queue.push(function () {


            var finished = callback();


            if (typeof finished === "undefined" || finished) {


                //  if callback returns `false`, then you have to 


                //  call `next` somewhere in the callback


                _this.dequeue();


            }


        });




        if (this.autorun && !this.running) {


            // if nothing is running, then start the engines!


            this.dequeue();


        }




        return this; // for chaining fun!


    };




    Queue.prototype.dequeue = function () {


        this.running = false;


        //get the first element off the queue


        var shift = this.queue.shift();


        if (shift) {


            this.running = true;


            shift();


        }


        return shift;


    };




    Queue.prototype.next = Queue.prototype.dequeue;




    return Queue;




})();





//Gọi hàm


var q = new Queue(false);


q.add(function() { /*function_1*/ });


q.add(function() { /*function_2*/ });


q.add(function() { /*function_3*/ });


.....


q.add(function() { /*function_n*/ });




setTimeout(function () { q.next();}, 2000);

Trả lời


📁 Code Demo