How to run 2 function at the same time in javascript?

by edmond_brakus , in category: Javascript , 25 days ago

How to run 2 function at the same time in javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer


by addison , 24 days ago


In JavaScript, you can't run two functions simultaneously in the same thread of execution as JavaScript is single-threaded. However, there are ways to achieve concurrent execution-like behavior using techniques like asynchronous programming, web workers, or Promises.

  1. Asynchronous Programming (using callbacks or async/await): You can run one function and then execute the other function inside a callback function or using async/await. Example: function function1(callback) { setTimeout(() => { console.log('Function 1'); callback(); }, 1000); } function function2() { console.log('Function 2'); } function1(function2);
  2. Promises: You can use Promises to run two functions concurrently and wait for both to complete. Example: function asyncFunction1() { return new Promise(resolve => { setTimeout(() => { console.log('Function 1'); resolve(); }, 1000); }); } function asyncFunction2() { console.log('Function 2'); } Promise.all([asyncFunction1(), asyncFunction2()]) .then(() => { console.log('Both functions completed.'); });
  3. Web Workers: Web Workers allow you to run JavaScript code in the background without blocking the main thread. Example: // In main.js const worker = new Worker('worker.js'); worker.postMessage('start'); worker.addEventListener('message', event => { console.log(; }); // In worker.js self.addEventListener('message', event => { if ( === 'start') { function1(); self.postMessage('Function 1 completed'); } });

These are just a few examples of how you can achieve concurrent-like behavior in JavaScript. The appropriate approach will depend on your specific requirements and the complexity of the functions you want to run.