0

I'm trying to implement a queue in javascript just like Google does. So far this is my code, I'm not sure if I'm doing it correctly or if there is a better way of doing it. Perhaps there is a name for doing it this way.

Here is my code:

var google = google || {};
google.cmd = google.cmd || [];

google.cmd.push(function() { alert("test"); });
google.cmd.push(function() { alert("test2"); });

function executeCmd() {
    for (k=0; k < google.cmd.length;k++){
        google.cmd[k]();
    }
    google.cmd.length = 0;
}

google.cmd.push = function(e) {
    Array.prototype.push.apply(this,arguments);
    executeCmd();
}
executeCmd();

google.cmd.push(function() { alert("test3"); });
t j
  • 7,026
  • 12
  • 46
  • 66
  • Welcome to Stack Overflow. Just two things about your question: 1) When you say a *que*, do you mean a *queue*? 2) What's exactly your question? – Jordi Nebot Nov 20 '17 at 14:40
  • Hi Jordi, Thank You, yes I mean a queue, My question is 1) if this is the correct way to handle a queue in javascript. 2) how do you call this kind of handeling a queue is there a name for it? I saw google do it this way so I tried to make a similar function. – GekkeHenkie Nov 20 '17 at 14:57
  • I don't know exactly what do you mean when you say "like google", but if you want to implement a queue in Javascript I suggest you to check tis other question: https://stackoverflow.com/questions/1590247/how-do-you-implement-a-stack-and-a-queue-in-javascript Yours is probably a duplicate. – Jordi Nebot Nov 20 '17 at 15:04
  • Hi Jordi, google says this about their function Reference to the global command queue for asynchronous execution of GPT-related calls. The googletag.cmd variable is initialized to an empty JavaScript array by the GPT tag syntax on the page, and cmd.push is the standard Array.push method that adds an element to the end of the array. When the GPT JavaScript is loaded, it looks through the array and executes all the functions in order. The script then replaces cmd with a googletag.CommandArray object whose push method is defined to execute the function argument passed to it. – GekkeHenkie Nov 20 '17 at 15:07
  • So what i actully want to do is load a javascript file async like this because you dont know when its loaded i want to make a queue like the code above and exequte it once the code is loaded. – GekkeHenkie Nov 20 '17 at 15:10
  • I'm sorry I'm not familiar with this terminology, but I'd recommend you to edit your question to add more information about your requirements and exact issues. Reading about [Asking](https://stackoverflow.com/help/asking) in SO help will probably be useful too. – Jordi Nebot Nov 20 '17 at 15:10
  • Cleaned up grammar and `queue` references. – t j Nov 21 '17 at 00:01

0 Answers0