纯js代码可在Firefox中运行,但不能在Chrome中运行

时间:2019-05-22 12:48:02

标签: javascript

下面的代码在Firefox中可以正常工作,在Chrome中,它表现得相当不错。对于短循环(几百个以下),它可以工作,但对于大循环,它永无止境。有时它可以从无限循环中突破并完成。

可以通过用_scope.context = undefined替换“删除_scope.context”来解决

有人可以详细说明这里发生了什么吗?

(function() {
  var _module = function() {
    const _scope = function() {
      var a = 0,
        block = 0;
      var suspend = function() {
        var context = {};
        context.a = a;
        context.block = block;
        context.resume = function() {
          _scope.context = context;
          return _scope();
        }
        _scope.context = context;
        return context;
      }
      var awake = function() {
        context = _scope.context;
        delete _scope.context;
        //_scope.context = undefined;
        a = context.a;
        block = context.block;
      }
      if (_scope.context !== undefined) {
        awake();
      }
      while (true) {
        switch (block) {
          case 0:
            block = 1;
            return suspend();
          case 1:
            block = 0;
            if (a++ > 10000) {
              return;
            }
            continue;
        }
      }
    }
    return _scope();
  }

  var runMod = function() {
    var susp = _module();
    var nSteps = 0;
    while (susp) {
      susp = susp.resume();
      if (!(++nSteps % 1000)) {
        console.log(nSteps, susp);
      }
      if (nSteps > 100000) {
        console.log('aborted')
        break;
      }
    }
    console.log('complete', nSteps);
  }

  runMod();
})()
.as-console-wrapper {
  max-height: 100% !important;
}

https://jsfiddle.net/daborkpw/

1 个答案:

答案 0 :(得分:0)