Home > Web Front-end > JS Tutorial > JavaScript uses yield to simulate multi-threading_javascript skills

JavaScript uses yield to simulate multi-threading_javascript skills

WBOY
Release: 2016-05-16 16:08:31
Original
1120 people have browsed it

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) {}
}
Copy after login

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
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template