制作国际象棋棋盘时的Javascript性能

时间:2015-06-14 07:44:39

标签: javascript performance

我用html表画棋盘(8x8),然后在棋盘上随机生成一个黄色单元格。这是代码:

$('#random').click(function(){
                for (i=0; i<100; i++){
                    setInterval(function(){
                        resetBoard(); // re-draw chess board without yellow cell
                        var index = Math.floor((Math.random() * 64));
                        $('.chess-board tr td').eq(index).css('background-color', 'yellow');    
            }, 150);
                }
});

黄色细胞的出现并未停止。并且该代码使浏览器计算非常多(我在任务管理器中看到Firefox在运行时使用32%的CPU)。 这有什么问题,谢谢兄弟?

3 个答案:

答案 0 :(得分:1)

您在for循环中不断初始化一系列新的 重复计时器 ,因此这些计时器功能最终会在一行中触发,每行之间的延迟非常小(不, 请)。因此,您的事件循环应该像这样大量繁忙:

  

时间间隔

           

T0 ........... 间隔#1 首次运行

     

T0 + 1 ......... 间隔#2 首次运行

     

T0 + 3 ......... 间隔#3 首次运行

     

...

     

T0 + 15 ........ 间隔#16 首次运行

     

.............. 间隔#1 重新运行

     

T0 + 16 ........ 间隔#17 首次运行

     

.............. 间隔#2 重播

     

....(很多间隔开始同意,让CPU忙碌)

如果您坚持使用计时器来延迟电路板的渲染。即使添加了新的计时器,也要继续重复计时器,这没有多大意义。我不确定你为什么需要这个。这会使您的任务倍增,使您的应用远离响应能力。

您最好使用超时来触发您的方案中的功能

您可能希望在上一个计时器完成后运行下一个计时器,而不是连续按顺序运行批量加载计时器。代码的框架可能如下所示:

var n=0;
function renderBoard(){
    resetBoard(); // re-draw chess board without yellow cell
    var index = Math.floor((Math.random() * 64));
    $('.chess-board tr td').eq(index).css('background-color', 'yellow');

    // After finish, add a delay of 150 ms to run the subsequent action
    n++;
    if (n<100)
       setTimeout(renderBoard, 150);
}

setTimeout(renderBoard, 150);

答案 1 :(得分:0)

您创建了100个间隔,每150毫秒运行一次!这是每秒666次(讽刺的是噢)......在每一次你重置电路板,并搜索DOM

$('.chess-board tr td')

应该在调用任何间隔之前缓存(保存到变量)。

你想用这些间隔做什么?

答案 2 :(得分:0)

$('#random').click(function(){
    var $chessCell = $('.chess-board tr td');
    for (i=0; i<100; i++){  // probably should not use this loop
      update();
    }
});
function update() {
        resetBoard(); // re-draw chess board without yellow cell
        var index = Math.floor((Math.random() * 64));
        $chessCell.eq(index).css('background-color', 'yellow');
        clearTimeout(timeout);
        setTimer(); 
}

function setTimer() {
  timeout = setTimeout(update, 150);
}
相关问题