javascript run two functions at the same time

How to Run Two Functions at the Same Time in JavaScript

As a web developer, I've come across several situations where I needed to run two functions at the same time in JavaScript. It's a common problem, especially when you're working with asynchronous code. In this post, I'll explain how you can run two functions at the same time in JavaScript.

Method 1: Using Promises

One of the easiest and most effective ways to run two functions at the same time is by using Promises. Promises are a built-in feature in JavaScript that help you handle asynchronous code. You can create two promises and use Promise.all() to run them at the same time.


const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Function 1');
  }, 2000);
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Function 2');
  }, 1000);
});

Promise.all([promise1, promise2]).then((results) => {
  console.log(results);
});

In the above example, we have created two promises that resolve after a certain amount of time. We use Promise.all() to wait for both promises to resolve and then log the results to the console. The output of this code will be:


["Function 1", "Function 2"]

Method 2: Using Async/Await

Another way to run two functions at the same time is by using Async/Await. Async/Await is a newer feature in JavaScript that allows you to write asynchronous code that looks synchronous. You can create two async functions and use Promise.all() to run them at the same time.


async function function1() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Function 1');
    }, 2000);
  });
}

async function function2() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Function 2');
    }, 1000);
  });
}

async function runFunctions() {
  const results = await Promise.all([function1(), function2()]);
  console.log(results);
}

runFunctions();

In the above example, we have created two async functions that return promises. We use Promise.all() to wait for both promises to resolve and then log the results to the console. The output of this code will be:


["Function 1", "Function 2"]

Method 3: Using Web Workers

If you're working with heavy computation, you can also use Web Workers to run two functions at the same time. Web Workers allow you to run JavaScript code in a separate thread, so it doesn't block the main thread. You can create two Web Workers and use postMessage() to communicate between them.


// main.js
const worker1 = new Worker('worker1.js');
const worker2 = new Worker('worker2.js');

worker1.onmessage = function(event) {
  console.log(event.data);
};

worker2.onmessage = function(event) {
  console.log(event.data);
};

worker1.postMessage('start');
worker2.postMessage('start');

// worker1.js
self.onmessage = function(event) {
  console.log('Function 1');
};

// worker2.js
self.onmessage = function(event) {
  console.log('Function 2');
};

In the above example, we have created two Web Workers that log a message when they receive a message from the main thread. We use postMessage() to send a message to both workers, which triggers them to log their respective messages. The output of this code will be:


Function 1
Function 2

Conclusion

These are some of the ways you can run two functions at the same time in JavaScript. Depending on your situation, one method may be more suitable than others. Promises and Async/Await are great for handling asynchronous code, while Web Workers are great for heavy computation.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe