如何在Javascript

时间:2015-11-09 11:00:43

标签: javascript multithreading worker

我正在编写一个Web流程来模拟Connect4棋盘游戏。我已经使用具有七列六行的Agile控制器进行了设置,每个单元格引用为c1r1,如下所示。

$scope.c1r1 = $scope.counterWhite;
$scope.c1r2 = $scope.counterWhite;
$scope.c1r3 = $scope.counterWhite;
.
.
$scope.c7r4 = $scope.counterWhite;
$scope.c7r5 = $scope.counterWhite;
$scope.c7r6 = $scope.counterWhite;

当用户点击任何单元格时,它会引发一个事件,我想显示计数器在可用单元格中丢失,代码如下所示

$scope.c1r1 = $scope.counterYellow;
setTimeout(fillC1(), 1000);        
$scope.c1r1 = $scope.counterWhite; 
$scope.c1r2 = $scope.counterYellow;

setTimeout(fillC1(), 1000);        
$scope.c1r2 = $scope.counterWhite; 
$scope.c1r3 = $scope.counterYellow;

setTimeout(fillC1(), 1000);        
$scope.c1r3 = $scope.counterWhite; 
$scope.c1r4 = $scope.counterYellow;

setTimeout(fillC1(), 1000);        
$scope.c1r4 = $scope.counterWhite; 
$scope.c1r5 = $scope.counterYellow;

setTimeout(fillC1(), 1000);        
$scope.c1r5 = $scope.counterWhite; 
$scope.c1r6 = $scope.counterYellow;

当我运行它没有任何反应时,计数器只显示在底部,所以我需要一个线程使其正常工作但由于JavaScript没有进行线程我想知道是否还有其他答案,如Web Workers。

2 个答案:

答案 0 :(得分:1)

是的,您设置单元格的方式是问题的一部分。

使用数组:

,而不是加载$scope.cXrY个变量
$scope.cells = [];
var x, y;
for(x = 0; x < 7; x ++){
    $scope.cells[x] = [];
    for(y = 0; y < 6; y ++){
        $scope.cells[x][y] = $scope.counterWhite;
    }
}

你去,一个变量中的所有单元格 而不是$scope.c2r4,而是使用$scope.cells[2][4]

现在,让计数器越过细胞:

function iterateOverCells(){
    fillC1()

    $scope.cells[x][y] = $scope.counterWhite; // Make the previous cell white

    x++;        // Get next cell position
    if(x >= 7){
        x = 0;
        y++;
    }

    $scope.cells[x][y] = $scope.counterYellow; // Current cell yellow
    if(x < 7 && y < 6)                         // If we're not at the last cell
        setTimeout(iterateOverCells, 1000);    // Go to the next cell in 1 second
}

var x = 0, y = 0;
$scope.cells[x][y] = $scope.counterYellow; // Make the first cell yellow
setTimeout(iterateOverCells, 1000);        // Next cell in 1 second

答案 1 :(得分:-1)

Web Workers无法访问DOM,它们用于计算。我不确定你为什么要使用后台话题,但是你可以这样做:

假设您编写了一个包含背景代码的脚本,该代码在完成内容后发布消息(将在一秒内回复:

function doWork() {
    postMessage("did something");
    setTimeout(doWork, 2000);
}
doWork();

现在,检查浏览器是否支持Web worker,创建一个,并监听从它发布的消息:

if(typeof(w) == "undefined") {
    executer = new Worker("background.js");
}
executer.onmessage = function(event){
    document.getElementById("results").innerHTML = event.data;
};

当你完成它之后,你可以像这样删除它: executer.terminate();