可以在一个页面中同时设置多少个javascript setTimeout / setInterval调用? [英] how many javascript setTimeout/ setInterval call can be set simultaneously in one page?
问题描述
我必须使用至少2个setTimeouts和1个setInterval。这是否依赖于所使用的浏览器或javascript引擎?
I have to use atleast 2 setTimeouts and 1 setInterval. Does this have any dependency on the browser or javascript engine being used?
推荐答案
在页面上,您可以根据需要同时运行多个setTimeouts / setIntervals,但是为了单独控制每个你需要将它们分配给一个变量。
On a page you can have as many setTimeouts/setIntervals running at once as you wish, however in order to control each individually you will need to assign them to a variable.
var interval_1 = setInterval("callFunc1();",2000);
var interval_2 = setInterval("callFunc2();",1000);
clearInterval(interval_1);
上述相同的代码适用于setTimeout,只需更换措辞。
The same code above applies to setTimeout, simply replacing the wording.
正如凯文所说,JavaScript确实是单线程的,所以虽然你可以让多个计时器同时打勾,但任何时候都只能有一个计时器 - 也就是说你有一个可以触发'停止'的功能'在执行中,例如使用警告框,然后JS必须'恢复',然后另一个可以触发我相信。
As Kevin has stated, JavaScript is indeed single threaded, so while you can have multiple timers ticking at once, only one can fire at any one time - i.e. if you have one that fires a function which 'halts' in execution, for example with an alert box, then that JS must be 'resumed' before another can trigger I believe.
下面给出了另一个例子。虽然标记无效,但它会显示超时的工作方式。
One further example is given below. While the markup is not valid, it shows how timeouts work.
<html>
<body>
<script type="text/javascript">
function addThing(){
var newEle = document.createElement("div");
newEle.innerHTML = "Timer1 Tick";
document.body.appendChild(newEle);
}
var t1= setInterval("addThing();",1000);
var t2 = setInterval("alert('moo');",2000);
</script>
</body>
</html>
这篇关于可以在一个页面中同时设置多少个javascript setTimeout / setInterval调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!