Wednesday, November 19, 2025
HomeLanguagesJavascriptHow to store JavaScript functions in a queue and execute in that...

How to store JavaScript functions in a queue and execute in that order?

In this article, the task is to execute the functions in the order defined in the queue with the help of JavaScript. There are two approaches that are discussed below.

Approach 1: Declare the functions and use the array push() method to push the functions in the array. Later traverse the array and execute the functions one by one.

Example: This example implements the above approach.

Javascript




function myGFG() {
 
    // First function
    function function1() {
        console.log("First Function");
    }
 
    // Second function
    function function2() {
        console.log("Second Function");
    }
 
    let orderQueue = [];
 
    // Push them in queue
    orderQueue.push(function1);
    orderQueue.push(function2);
 
    while (orderQueue.length > 0) {
     
        // Execute in order
        orderQueue.shift()();
    }
 
    console.log("Functions executed in queue order");
}
 
myGFG();


Output

First Function
Second Function
Functions executed in queue order

Approach 2: Declare the functions and use array indexing to assign the functions to index of the array in the order. Later traverse the array and execute the functions one by one.

Example: This example implements the above approach. 

Javascript




function myGFG() {
 
    // First function
    function function1() {
        console.log("First Function");
    }
 
    // Second function
    function function2() {
        console.log("Second Function");
    }
 
    let functions = new Array();
 
    // Adding the functions in the order
    // in queue(array)
    functions[0] = function1;
    functions[1] = function2;
     
    for (let i = 0; i < functions.length; i++) {
 
        // Executing them in order.
        functions[i].call();
    }
     
    console.log("Functions executed in queue order");
}
 
myGFG();


Output

First Function
Second Function
Functions executed in queue order
RELATED ARTICLES

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6775 POSTS0 COMMENTS
Nicole Veronica
11924 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6903 POSTS0 COMMENTS
Ted Musemwa
7159 POSTS0 COMMENTS
Thapelo Manthata
6859 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS