是否有某种window.onThis();
函数,我可以设置,以便我的代码在后台循环运行?Javascript的后台运行代码
window.onload = function() {while(true) {console.log("Blah")}}
这会使页面无响应。推荐的方法是什么?
我觉得有些事情已经过去了。也许我看错了方式。
是否有某种window.onThis();
函数,我可以设置,以便我的代码在后台循环运行?Javascript的后台运行代码
window.onload = function() {while(true) {console.log("Blah")}}
这会使页面无响应。推荐的方法是什么?
我觉得有些事情已经过去了。也许我看错了方式。
Javascript一次只能运行一个线程,所以当它以最快的速度运行console.log ("Blah")
时,它无法做任何事情。
更好的方法是使用setInterval
,例如,
var a = setInterval(function() { console.log("blah"); }, 1000);
// Set the function to be called every 1000 milliseconds
//(optional) some time later
clearInterval(a);
// Stop the function from being called every second.
一般来说,繁忙的无限循环(while (true) { ... }
)是不是一个好主意。
见https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
如何使用Javascript /帆布游戏更新如此之快?他们做什么来更新每一帧的显示,但没有滞后页面? –
这使得页面反应迟钝,因为你已经创建了一个无限循环。 while循环条件将始终为真,因此循环永远不会停止运行。
我认为你正在寻找的setInterval(),在这里看到https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
http://en.wikipedia.org/wiki/Web_worker – Musa