简体   繁体   English

我的 Javascript 代码使用了 100% 的 CPU 并且无法加载

[英]My Javascript code uses 100% of my CPU and doesn't load

I was trying to make a little game with text.我试图用文字制作一个小游戏。 After running the code Game.start() function I lagged and nothing happen.运行代码 Game.start() function 后,我落后了,没有任何反应。 I think that is the for loop.我认为这是 for 循环。 Please help me Here's my code:请帮助我这是我的代码:

    class unit {
  constructor(health, speed, x, y) {
    this.health = health;
    this.speed = speed;
    this.x = x;
    this.y = y;
  }
  moveTo(xval, yval) {
    this.x = xval;
    this.y = yval;
  }
}

var player = new unit(100, 1, 10, 10);
var unit1 = new unit(50, 1, 1, 12);
var unit2 = new unit(50, 1, 2, 4);
var unit3 = new unit(50, 1, 3, 6);

var i = 0;
var units = 4;
var u = [player, unit1, unit2, unit3];
var k, l, t, r;

function draw(txt) { document.write(txt); };

var Game = {
  width : 20, // Largeur
  height : 20, // Hauteur

  start : function() {
    for(t = 0; t < this.height++; t++) {
    for(k = 0; k < this.width++; k++) {
      for(var x1 = 0; i < units; x1++) {
        if(u[k].x != k) {
          draw('#');
        } else {
          draw('%');
        }
      }
    }
  }
 }
}

Because in your third for statement in start function, your exit condition relies on i while you update x1 on each loop, so you have an infinite loop.因为在start function 中的第三个for语句中,当您在每个循环上更新x1时,您的退出条件依赖于i ,因此您有一个无限循环。

If you're testing IE and have an empty variable ( var =; ) it will freeze the browser so be sure to look at your JavaScript output, especially if you're using server code to generate values.如果您正在测试 IE 并且有一个空变量 ( var =; ),它将冻结浏览器,因此请务必查看您的 JavaScript output,尤其是在您使用服务器代码生成值的情况下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM