本文实例讲述了JavaScript使用yield模拟多线程的方法。分享给大家供大家参考。具体分析如下:

在python和C#中都有yield方法,通过yield可以实现很多多线程才能实现的功能。
对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) {}
}

上面代码输入结果如下:

foo: 0
bar: 0
foo: 1
bar: 1
foo: 2
bar: 2
foo: 3
bar: 3
foo: 4
bar: 4

希望本文所述对大家的javascript程序设计有所帮助。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com