javascript中的同时代码? [英] Simultaneous code in javascript?

查看:95
本文介绍了javascript中的同时代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何同时运行两个单独的功能?如果我想要两个时钟,一个计数,另一个计数,我想让它们同时运行,我该怎么做?

How do I have two separate functions run simultaneously? If I wanted two clocks, one to count up and the other to count down, and I wanted them to run at the same time, how would I do it?

如果我刚刚做了:

var up = 1;
while(true){
    document.write(up);
    up++;
    if(up==11)
        up=1;
}
var down = 10;
while(true){
    document.write(down);
    down--;
    if(down==0)
        down=10;
}

...它会继续计算......

...it would just keep counting up...

推荐答案

Javascript是单线程的。只有一个线程可以访问该页面。

Javascript is single threaded. There is only one thread that can ever access the page.

在某些HTML5浏览器中可以使用 Web Workers 在另一个线程中执行一些代码,然后通过消息传递与主线程通信,但Web Worker线程无法访问DOM以任何方式。

It is possible in some HTML5 browsers to use Web Workers to execute some code in another thread and then communicate with the main thread via messaging, but the Web Worker thread cannot access the DOM in any way.

如果你想让计数器在循环中运行,那么这种方法的典型方法是使用计时器,然后在DOM中设置对象的内容。每次计时器运行。通过这种方式,您可以看到同时运行多个事物,但实际上,它们仍然是一次一个,只是单独计时。

If you want counters to run in a loop, the typical way of doing that is by using timers and then setting the contents of an object in the DOM each time the timer goes. In this way, you can appear to have multiple things running at the same time, but in reality, they are still one at a time, just separately timed.

这是一个看起来同时运行的两个计数器的示例: http://jsfiddle.net/jfriend00/ 3yc9r /

Here's an example of two counters that "appear" to be running at the same time: http://jsfiddle.net/jfriend00/3yc9r/.

这个代码就是这个(在页面加载后运行):

The code for that is this (run after the page is loaded):

var cntr1 = 1;
var cntr2 = 2;

setInterval(function() {
    document.getElementById("time1").innerHTML = cntr1 += 13;
}, 33);

setInterval(function() {
    document.getElementById("time2").innerHTML = cntr2 += 5;
}, 44);

另外,你真的不想做 document.write( )循环中的。将运行一段时间的代码应在页面加载后运行,并且应该直接修改DOM中的对象,而不是使用 document.write()

Also, you really don't want to be doing document.write() in a loop. Code that's going to run for awhile should run after the page is loaded and should modify objects in the DOM directly rather than use document.write().

这篇关于javascript中的同时代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆