iframe 加载事件中的 setTimeout 似乎没有像预期的那样等待 x 秒

setTimeout inside iframe load event doesn't seem to wait x seconds as expected

本文关键字:等待 事件 加载 setTimeout iframe      更新时间:2023-09-26

我想在加载 iframe 后几秒钟后触发 doSomething(),但它会立即触发 doSomething,为什么?

    <html>
    <iframe id="myIframe"  src="myFrame.html" width=100% height=600></iframe>
    <script>
    iframe = document.getElementById("myIframe");
    function doSomething() {
      alert("it should have wait 5000 milliseconds, instead it triggers immediately");
    }
    if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera) {
      var oldonreadystatechange = iframe.onreadystatechange;
      iframe.onreadystatechange = function(){
        if (iframe.readyState == "complete"){
          if (oldonreadystatechange != null) {
            oldonreadystatechange();
            setTimeout(doSomething(),5000);
          }
        }
      };
    } else {
      var oldonload = iframe.onload;
      iframe.onload = function(){
        if (oldonload != null) {
          oldonload();
        }
        setTimeout(doSomething(),5000);
      };
    }
    </script>
    </html>

如果你还想传递参数,一个非常简单的方法是为 setTimeout 创建一个新的匿名函数,如下所示:

setTimeout(function(){ doSomething(123, anotherParam) }, 5000);

这是因为在 JavaScript 中,如果你将函数作为参数传递给另一个函数,比如 someFunction(otherFunction());你正在将该函数的执行结果传递给 someFunction。

您要做的是将该函数的引用提供给 setTimeout,以便 setTimeout 决定何时运行它。

这样做:

setTimeout(doSomething, 5000);

除非我完全错过了什么,否则如果您只是在 iframe 的加载事件上触发,您可以使用以下内容来减少该代码:

document.getElementById('myIframe').onload = function() {
   setTimeout(doSomething, 5000);
}

片段

<iframe id="myIframe" src="/" width=100% height=600></iframe>
<script>
  iframe = document.getElementById("myIframe");
  function doSomething() {
    alert("it should have wait 5000 milliseconds, instead it triggers immediately");
  }
  iframe.onload = function() {
    setTimeout(doSomething, 5000);
  }
</script>