【问题标题】:How to run a function with a setTimeout() callback inside iframe when this setTimeout() calls another setTimeout() in parent?当此 setTimeout() 在父级中调用另一个 setTimeout() 时,如何在 iframe 内运行带有 setTimeout() 回调的函数?
【发布时间】:2019-08-06 20:54:50
【问题描述】:

我的页面上有一个动态创建的 iframe。像这样:

var iframe = document.createElement('iframe');
iframe.setAttribute("id","myIframe");
iframe.src = "iframePage.html";
document.body.appendChild(iframe);

在“iframePage.html”中,我有在 mainPage.html 上运行的相同 scriptfile.js。所以,我可以调用一个或另一个页面中的所有函数。

在这个 scriptfile.js 中,我有这个由“iframePage.html”上的按钮调用的函数。该函数在 1 秒内从 DOM 中删除 iframe!就像这样:

function closeAndRemoveIframe() {
   setTimeout(function() {
      var myIframe = window.parent.document.getElementById("myIframe");
      myIframe.parentNode.removeChild(myIframe);
   },1000);
}

好的。 但是我在这个函数中添加了对另一个函数的调用。但是这个函数包含一个 setTimeout,它会产生 3 秒的延迟。

就像这样:

function closeAndRemoveIframe() {
   setTimeout(function() {
      var myIframe = window.parent.document.getElementById("myIframe");
      myIframe.parentNode.removeChild(myIframe);
      myNewFunction();
   },1000);
}

问题是: 这个新函数具有更长的运行时间 setTimeout(3000 毫秒)。

function myNewFunction() {
   setTimeout(function() {
      console.log("Hello world");
   },3000);
}

iframe 是调用“myNewFunction()”函数的那个​​。并且一旦它在 1 秒后从 DOM 中移除,新功能就不会发生,因为它有 3 秒的延迟!

我找到的唯一解决方案是将相同的时间放在第一个函数的 setTimeout 中!但这不是理想的行为!

那么,有没有什么办法可以解决这个问题而不必增加第一个函数的settimeout时间呢?

P.s:我正在使用 vanilla JS

非常感谢!

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您是否尝试过将myNewFunction 调用移到removeChild 函数调用之前?

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 2022-01-03
      • 2021-03-04
      相关资源
      最近更新 更多