Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneous code in javascript?

Tags:

javascript

How do I have two separate functions run simultaneously? If I wanted two clocks, one to count up and the other to count down, and I wanted them to run at the same time, how would I do it?

If I just did:

var up = 1;
while(true){
    document.write(up);
    up++;
    if(up==11)
        up=1;
}
var down = 10;
while(true){
    document.write(down);
    down--;
    if(down==0)
        down=10;
}

...it would just keep counting up...

like image 414
mowwwalker Avatar asked Aug 10 '11 00:08

mowwwalker


People also ask

How to run two process simultaneously in JavaScript?

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.

Can JavaScript run concurrently?

Multiprocessing in JavaScript is mostly executed in server-side technology, as it allows more than one Node instance to run concurrently.

How do you run a JavaScript function in parallel?

This is not possible. Javascript can only work in a single thread and there is no way to actually have two functions running in parallel. You need to make one call and then the other.

What is concurrency model in JavaScript?

Concurrency means that a program is able to run more than one task at a time — this is not to be confused with parallelism. During concurrency, different tasks with differing goals of the program can be performed at the same time, while in parallelism, different parts of the program execute one task.


1 Answers

Javascript is single threaded. There is only one thread that can ever access the page.

It is possible in some HTML5 browsers to use Web Workers to execute some code in another thread and then communicate with the main thread via messaging, but the Web Worker thread cannot access the DOM in any way.

If you want counters to run in a loop, the typical way of doing that is by using timers and then setting the contents of an object in the DOM each time the timer goes. In this way, you can appear to have multiple things running at the same time, but in reality, they are still one at a time, just separately timed.

Here's an example of two counters that "appear" to be running at the same time: http://jsfiddle.net/jfriend00/3yc9r/.

The code for that is this (run after the page is loaded):

var cntr1 = 1;
var cntr2 = 2;

setInterval(function() {
    document.getElementById("time1").innerHTML = cntr1 += 13;
}, 33);

setInterval(function() {
    document.getElementById("time2").innerHTML = cntr2 += 5;
}, 44);

Also, you really don't want to be doing document.write() in a loop. Code that's going to run for awhile should run after the page is loaded and should modify objects in the DOM directly rather than use document.write().

like image 170
jfriend00 Avatar answered Dec 31 '22 19:12

jfriend00