3

Is it possible to call multiple functions at the same time?

E.g.

var executed = false;
// loop 1
func();
// loop 2
func();

function func(){
    if (executed) return;
    executed = true;
    alert(1);
}

Can func() be executed 2 times at once?

jan-seins
  • 1,253
  • 1
  • 18
  • 31
user234
  • 99
  • 1
  • 1
  • 8
  • 3
    Javascript is like most programming languages, everything is executed in order, unless you explicitly use something that runs asynchronously or uses threads (e.g. Javascript WebWorkers). – Barmar Jun 09 '17 at 19:58
  • 1
    When you write `func(); func();`, it doesn't execute the second call until the first call returns. – Barmar Jun 09 '17 at 19:59
  • @Barmar unless they are async – Paul Jun 09 '17 at 20:00
  • 2
    JavaScript has no (standard) provision for concurrent execution contexts (ie. "threads") that can interact. Asynchronicity and concurrency are different. Therefore, "at the same time" should be better qualified. – user2864740 Jun 09 '17 at 20:00
  • Node JS is the closest thing I know of to true async – Stephen J Jun 09 '17 at 20:01
  • @StephenJ Ajax calls and webworkers and web sockets are effectively async as well, from most modern browsers. – Paul Jun 09 '17 at 20:01
  • Welcome to StackOverflow! Can you provide some more information? You said "multiple functions at the same time" however your code snippet shows the same function called twice which is not the same thing. – styfle Jun 09 '17 at 20:03
  • @user234 yes. But the functions still dont run at the same time. – Jonas Wilms Jun 09 '17 at 20:05
  • @Jonasw Shouldn't `if (executed) return;` prevent `alert(1)` from running? – user234 Jun 09 '17 at 20:07
  • @Paul You have to do something explicitly to make them async, like the `async` keyword on the function definition. – Barmar Jun 09 '17 at 20:07
  • @user234 Yes, of course it does. When the function returns, it stops executing. This is really basic stuff, common to almost all programming languages. – Barmar Jun 09 '17 at 20:08
  • @user234 yes, one needs to modify the code. Your current function can never by run twice at once ( no one can really), and also not twice if theres no change to executed – Jonas Wilms Jun 09 '17 at 20:08

4 Answers4

3

No processor i know can execute statements at the same time. Most computers have multiple processors, so they can run multiple statements on multiple processors. So the only possible solution would be opening your browser twice, open the same page and hope that the js is executed parallel ( or use some fancy NodeJS or WebWorkers etc.).

However instead of running the same time , its common to switch between two threads very fast, so that it looks like being the same time (called multitasking). You could do this in js like this:

var executed = false;
var theother=new Promise( r=>setTimeout(r,0));
func();
// loop 2
func();

async function func(){
if (executed) return;
await theother;
executed = true;
alert(1);
}

Or old style ( to resolve the magic ):

var executed = false;
// loop 1
func();
// loop 2
func();

function func(){
if (executed) return;
setTimeout(function(){
  executed = true;
  alert(1);
 },0);
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
3

JavaScript has no native support for running multiple functions simultaneously. It has, historically, depended on time-consuming tasks (such as waiting for an HTTP request or doing something CPU intensive) being handled with native code that presents an API to JS (and that API accepting a callback or, more recently, returning a Promise).

That is starting to change.

Most web browsers support Web Workers and Node.js has introduced experimental support for Worker Threads.

These each allow JavaScript code to be farmed off to a separate process which runs independently of the main event loop and communicate with the main process using messages.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You can't do this. Because JavaScript does not support multi-threading. Every tab of web browser just have a single interpreter and JavaScript interpreter in the browser is a single thread. See an example of single thread here.

See also this answer.

MahdiY
  • 1,269
  • 21
  • 32
-3

Use below code

<!DOCTYPE html>
<html>
<head>
    <title>sample test</title>
    <script type="text/javascript">

        print=function(msg) {
            var ifunction=function(){
                console.log(msg);
            }
            return ifunction;
        };

        button1=function(name,count){
                for (var i =0 ;i <count; i++) {
                    setTimeout(print(name+":"+i+"seconds over after button1 click"),i*500);
                }
        };

    </script>
</head>
<body>
    <form>
        <input type="" name="" />
        <input type="button" value="button1" onclick="button1('button1',5)" />
        <input type="button" value="button2" onclick="button1('button2',5)" />
    </form>
</body>
</html>