0

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

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

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

我觉得有什么东西在我头上。也许我看错了。

4

2 回答 2

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

于 2013-08-04T22:23:30.327 回答
0

它使页面无响应,因为您创建了一个无限循环。while 循环条件将始终为真,因此循环将永远不会停止运行。

我认为您正在寻找 setInterval(),请参见此处https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval

于 2013-08-04T22:23:35.727 回答