0

我希望 Javascript 代码可以无限地操作 html 中的某些对象,

但是,我只能用setTimeout("function()", 0)不能用while(1)

例子

whilehttps ://gist.github.com/Asoul/e5dd3bd38eef4ca239cb

setTimeouthttps ://gist.github.com/Asoul/bda34fa2f70e4077ec12

我不知道为什么while(1)不能在我的 chrome 上工作

SetTimeout有时可以工作,但如果我的代码中有很多setTimeout或一些未知原因,它会滞后。

示例http ://www.csie.ntu.edu.tw/~b00902036/run_neo/run_neo.html

(用尽,左,右玩。我努力避免滞后,但有时仍然会发生。)

我想使用纯 CSS,而不是画布,并且希望游戏可以毫无延迟地玩。

4

1 回答 1

3

The main reason you cannot use while is because javascript is single-threaded. If you use while(1), the function will never exit and all other interactions are frozen.

SetTimeout can work sometimes, but if there are many setTimeout in my code or some unknown reasons, it will lag.

This is also because of single-threaded nature of javascript, if there is a function taking long time to complete, it will dominate the main thread.

want the game can play without lags.

You need to avoid long-running operation inside all of your functions. If you cannot avoid that, try using setTimeout to split a long-running operation into many pieces. For example: if you have a for-loop processing 100 records, you could split it into 10 separate iterations.

于 2013-10-06T07:55:08.807 回答