Skip to content Skip to sidebar Skip to footer

Can Javascript Run Multiple Functions At Once?

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

Solution 1:

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=newPromise( r=>setTimeout(r,0));
func();
// loop 2func();

asyncfunctionfunc(){
if (executed) return;
await theother;
executed = true;
alert(1);
}

Or old style ( to resolve the magic ):

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

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

Solution 2:

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.

Solution 3:

Use below code

<!DOCTYPE html><html><head><title>sample test</title><scripttype="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><inputtype=""name="" /><inputtype="button"value="button1"onclick="button1('button1',5)" /><inputtype="button"value="button2"onclick="button1('button2',5)" /></form></body></html>

Post a Comment for "Can Javascript Run Multiple Functions At Once?"