setTimeout() - 匿名函数语法在页面加载时触发两次

setTimeout() - anonymous function syntax fires twice on page load

以下是我的 index.html 文件及其包含的 script.js 文件的示例:

main();

function main() {
  if (document.readyState == 'complete') {
    console.log('test');
  } else {
    setTimeout(function() {
      main();
    }, 1000);
    //setTimeout('main', 1000);
  }
}
<!DOCTYPE html>
<html>

<head>
  <script type="text/javascript" src="scripts.js"></script>
</head>

<body onload="javascript: main();">
</body>

</html>

出于某种原因,setTimeout(function() { main(); }, 1000); 调用了 main() 两次,而 setTimeout('main', 1000); 调用了一次。两者不应该产生相同的结果吗?我错过了什么?

您的代码是 运行 main() 两次。一次在 js 文件的第一行,一次在 body 标签的 onload 属性中。

我建议您从 body 标记中删除 onload 处理程序。

其实并没有按照你的想法去做。 setTimeout('main', 1000) 什么都不做,因为它是无效代码。应该是 setTimeout(main, 1000).

它看起来像 运行 两次的原因是因为您的 body 标记中有 onload="javascript: main();",并且还在 [=] 的顶部调用了 main(); 19=].

您的 <body onload="javascript: main();"> 调用了一次函数,并且还在 JavaScript 代码的开头调用了 main 函数。