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...
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.
Multiprocessing in JavaScript is mostly executed in server-side technology, as it allows more than one Node instance to run concurrently.
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.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With