Home >Web Front-end >JS Tutorial >JavaScript uses yield to simulate multi-threading_javascript skills
The example in this article describes how JavaScript uses yield to simulate multi-threading. Share it with everyone for your reference. The specific analysis is as follows:
There are yield methods in python and C#, and many functions that can only be achieved by multi-threading can be achieved through yield.
There are version requirements for javascript: JavaScript 1.7
function Thread( name ) { for ( var i = 0; i < 5; i++ ) { Print(name+': '+i); yield; } } //// thread management var threads = []; // thread creation threads.push( new Thread('foo') ); threads.push( new Thread('bar') ); // scheduler while (threads.length) { var thread = threads.shift(); try { thread.next(); threads.push(thread); } catch(ex if ex instanceof StopIteration) {} }
The result of inputting the above code is as follows:
foo: 0 bar: 0 foo: 1 bar: 1 foo: 2 bar: 2 foo: 3 bar: 3 foo: 4 bar: 4
I hope this article will be helpful to everyone’s JavaScript programming design.