[英]Javascript background running code
Is there some sort of window.onThis();
是否有某种
window.onThis();
function that I can set so that my code runs in a loop in the background? 我可以设置的功能,以便我的代码在后台循环运行?
window.onload = function() {while(true) {console.log("Blah")}}
This makes the page unresponsive. 这会使页面无响应。 What is the recommended method of doing this?
这样做的推荐方法是什么?
I feel something's going over my head. 我觉得有些事情在我脑海里浮现。 Perhaps I'm looking at it the wrong way.
也许我正在以错误的方式看待它。
Javascript can only run one thread at a time, so when it is running console.log ("Blah")
forever as fast as possible, it is unable to do anything else. Javascript一次只能运行一个线程,因此当它尽可能快地运行
console.log ("Blah")
,它无法执行任何其他操作。
A better way would be to use setInterval
, eg 更好的方法是使用
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.
In general, a busy infinite loop ( while (true) { ... }
) is never a good idea. 一般来说,繁忙的无限循环(
while (true) { ... }
)绝不是一个好主意。
See https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval 请参阅https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
It makes the page unresponsive because you've created an infinite loop. 它使页面无响应,因为您创建了一个无限循环。 The while loop condition will always be true therefore the loop will never stop running.
while循环条件始终为true,因此循环永远不会停止运行。
I think you are looking for setInterval(), see here https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval 我想你正在寻找setInterval(),请看这里https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.