2013-08-04 61 views
0

是否有某种window.onThis();函数,我可以设置,以便我的代码在后台循环运行?Javascript的后台运行代码

window.onload = function() {while(true) {console.log("Blah")}} 

这会使页面无响应。推荐的方法是什么?

我觉得有些事情已经过去了。也许我看错了方式。

+2

http://en.wikipedia.org/wiki/Web_worker – Musa

回答

2

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

+0

如何使用Javascript /帆布游戏更新如此之快?他们做什么来更新每一帧的显示,但没有滞后页面? –