Skip to content
the poor coder

javascript run two functions at the same time

Poor Man
Published
Reading time
3 min read
On this page

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.

Text

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:

Text

["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.

Text

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:

Text

["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.

Text

// 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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC