为什么由不应立即运行的JavaScript函数引起一些延迟?

时间:2019-05-16 04:40:12

标签: javascript synchronization settimeout delay

我有两个功能,showhidegetSourceCode。我希望showhide在提交后立即执行(隐藏对话框),但是getSourceCode相当长,因此我稍后再执行。但是,在我单击提交和showhide生效之间仍然存在一些延迟。当我删除getSourceCode时,对话框可以立即消失,但是只要有getSourceCode,即使我setTimeout,对话框也总是被延迟。

document.querySelector("[type=submit]").onclick = function (event) {

    showhide('dialogBox');

    if (options[0].checked) {
          setTimeout(getSourceCode(),10000);          
    }
}

function getSourceCode() {

    var htmlastext = ajax("something.aspx");

    function HTML(text) {

        this.fullCode = (new DOMParser()).parseFromString(text, "text/html");
        this.scripts = this.fullCode.querySelectorAll("script[src]");
        this.style = this.fullCode.querySelector("link[rel=stylesheet]");
        this.images = this.fullCode.querySelectorAll("img");

        this.replaceContent = function (content, element, tag) {
            var newElement = this.fullCode.createElement(tag);
            newElement.innerHTML = content;
            element.parentNode.replaceChild(newElement, element);
        }

        this.modify = function () {

            var externalContent;
            var serverpath = window.location.origin;

            for (var i = 0; i < this.scripts.length; i++) {
                externalContent = ajax(this.scripts[i].src.slice(serverpath.length));
                this.replaceContent(externalContent, this.scripts[i], "script");
            }

            externalContent = ajax(this.style.href.slice(serverpath.length));
            this.replaceContent(externalContent, this.style, "style");


            var removeTagList = [
                this.fullCode.getElementById("logout"),
                this.fullCode.getElementById("saveHTML"),
                this.fullCode.getElementById("dialogOverlay"),
                this.fullCode.querySelectorAll("script")[4],
                this.fullCode.querySelector("link")
            ];

            for (i=0; i<removeTagList.length; i++) {
                removeTagList[i].parentNode.removeChild(removeTagList[i]);
            }
        }
    }

    var htmlDoc = new HTML(htmlastext);
    var html = htmlDoc.fullCode;
    htmlDoc.modify();
    htmlastext = (new XMLSerializer()).serializeToString(html);

    var txtarea = document.createElement("textarea");
    txtarea.innerHTML = htmlastext;
    htmlastext = txtarea.value;
    document.getElementById("encodedSourceCode").value = btoa(htmlastext);

}

为什么showhide中会发生延迟? JavaScript函数不同步吗? setTimeOut是否无法阻止参数函数在超时之前执行?如何在提交后立即隐藏对话框而不删除getSourceCode

1 个答案:

答案 0 :(得分:0)

问题出在这一行:

setTimeout(getSourceCode(),10000);

由于getSourceCode函数立即被调用(由于之后是()),只有其返回值传递给了setTimeout

删除函数后的括号,然后,函数将被传递给setTimeout,并在内部进行调用。

setTimeout(getSourceCode,10000);