PUSHLET 实战:JavaScript下利用setTimeout调度

<body>
<div id="content" />
</body>
<SCRIPT LANGUAGE="JavaScript">
<!--
function main()
{
    for (var i = 0; i < 10; i++)
    {
        setTimeout("print('" + i + "')", 0);
        print("main");
    }
}

function print(identity)
{
    var ele = document.getElementById("content");
    ele.innerHTML += " print " + identity + "<br>";
}

main();
//-->
</SCRIPT>

 这阶段看PUSHLET的源码,对JS不是很熟,知道JavaScript默认只是单线程执行的,它总是执行完一个函数后才去执行另一个函数。但是看到一段代码:

// Join the pushlet server
function p_join() {
	// Ignore (for now) if already joined
	if (sessionId != null) {
		return;
	}

	_setStatus('connecting...');
	p_debug(flag, "p_join", 'joining..');


  // Check if pushlet frame is loaded
	if (pushletNet) {
		// Pushlet iframe is ready for calls
		pushletNet.setControlURI(pushletURI + '?p_event=join');
	} else {

		// Pushlet net iframe not loaded: continue waiting
		setTimeout("p_join()", 100);
	}
}

 

发现如果pushletNet没有初始化的话,那么如果继续执行setTimeout("p_join()", 100);而不执行其他函数岂不是永远循环下去,肯定是引擎做了调度,做了个最上面的测试代码,发现果然如我所猜。

你可能感兴趣的:(JavaScript,.net)