Concurrent code in javascript?

How do I run two separate functions at the same time? If I wanted two hours, one for counting and one for a countdown, and I wanted them to start 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; } 

... he would just keep counting ...

+6
source share
4 answers

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

In some HTML5 browsers, you can use Web Workers to execute some code on another thread, and then exchange messages with the main thread through messaging, but the Web Worker stream cannot access the DOM in any way.

If you want counters to be executed in a loop, a typical way to do this is to use timers, and then set the contents of the object in the DOM every time a timer runs. Thus, you may have several things running at the same time, but in reality they are still one at a time, just separately.

Here is an example of two counters that β€œappear” at the same time: http://jsfiddle.net/jfriend00/3yc9r/ .

The code for this (runs after the page loads):

 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 do document.write() in a loop. Code that will run for a while should run after the page loads and should modify objects directly in the DOM, rather than using document.write() .

+9
source

You will need to put both counters in the same loop, but JavaScript is essentially single-threaded, your sample code will freeze the browser. Try using the SetTimeout or SetInterval function to fire the event at a specific interval. http://www.w3schools.com/js/js_timing.asp

+2
source

Not. Javascript is single threaded. If you need a clock, you will use asynchronous timeouts.

 // Counts up and down by one per second. var up = 1; setTimeout(function() { up++; document.write(up); }, 1000); var down = 10; setTimeout(function() { down--; document.write(down); }, 1000); 

JS can only do one thing at a time (which means in a single threaded run loop), but it combines asynchronous callbacks very well.

+2
source

You cannot, and if you write a body in a loop, it will be slow.

Instead, use setTimeout () to start the next iteration of the forever loop. https://developer.mozilla.org/en/window.setTimeout

+1
source

Source: https://habr.com/ru/post/894686/


All Articles