Javascript performance when making chess board -
i use html table draw chess board(8x8), generate yellow cell appear randomly in chess board. code:
$('#random').click(function(){ (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); } });
the appearence of yellow cell doesn't stop. , code make browser compute (i saw in task manager firefox use 32% cpu while run this). problem in this, thank bro ?
you keep initializing sequence of new repetitive timers in loop timer functions triggered in row small delay between each of them (no, please). thus, event loop should massively busy this:
time lapse
t0 ........... interval#1 first runs
t0+1 ......... interval#2 first runs
t0+3 ......... interval#3 first runs
...
t0+15 ........ interval#16 first runs
.............. interval#1 reruns
t0+16 ........ interval#17 first runs
.............. interval#2 reruns
.... (lots of intervals start concur, keep cpu busy)
if insist use timer delay render of board. keep repeating timer though new timers being added in not make sense. i'm not sure why need this. multiplying tasks , makes app far responsiveness.
you should better use timeout trigger function in scenario
you may want run next timer once previous timer finishes instead of sequentially run bulk load of timers continuously. skeleton of code may this:
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 delay of 150 ms run subsequent action n++; if (n<100) settimeout(renderboard, 150); } settimeout(renderboard, 150);
Comments
Post a Comment