我只发现了涉及类,事件处理程序和回调的相当复杂的答案(在我看来,这似乎是一个有点大锤的方法).我认为回调可能有用但我似乎无法在最简单的上下文中应用这些.看这个例子:
<html>
<head>
<script type="text/javascript">
function myfunction() {
longfunctionfirst();
shortfunctionsecond();
}
function longfunctionfirst() {
setTimeout('alert("first function finished");',3000);
}
function shortfunctionsecond() {
setTimeout('alert("second function finished");',200);
}
</script>
</head>
<body>
<a href="#" onclick="javascript:myfunction();return false;">Call my function</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在此,第二个函数在第一个函数之前完成; 什么是最简单的方法(或者有一个?)强制第二个函数延迟执行直到第一个函数完成?
- -编辑 - -
所以这是一个垃圾的例子,但多亏了David Hedlund,我看到这个新的例子确实它是同步的(同时在测试过程中崩溃我的浏览器!):
<html>
<head>
<script type="text/javascript">
function myfunction() {
longfunctionfirst();
shortfunctionsecond();
}
function longfunctionfirst() {
var j = 10000;
for (var i=0; i<j; i++) {
document.body.innerHTML += i;
}
alert("first function finished");
}
function shortfunctionsecond() {
var j …Run Code Online (Sandbox Code Playgroud)