确定布尔值何时从true更改为false

时间:2015-06-01 21:07:18

标签: javascript html

我有一个有打印按钮的网页。按下打印按钮后,我有一个功能

function pWindowNeeded() {
    if (newPWindowNeeded == 'Y') {
        return true;
    }
    return false;
}

然后我有另一个函数,如果它是真的那么打开一个包含要打印的PDF的新窗口并将newPWindowNeeded更改为'N'<​​/ p>

这一切都很好。

此时,当用户点击打印窗口时,我正在运行此功能

function alertWindow()
{
    var w = window.open('','',' width = 200, height = 200, top = 250 , left = 500 ');
    w.document.write("Please Wait<br> Creating Document(s).<br><img src='loadingimage.gif'>");
    w.focus();
    setTimeout(function() {w.close();}, 5000);
}

这也可以正常工作,窗口已创建,然后在5秒后自动关闭。

现在这样可以正常工作但我真正需要的是评估pWindowNeeded何时返回false以及何时返回false我需要它自动关闭窗口。

当pWindowNeeded从true更改为false时,最有效的方法是什么?

由于

1 个答案:

答案 0 :(得分:1)

效率最低且最简单的方法是使用setTimeout轮询值。

function callbackWhenWindowNotNeeded(cb) {
    if (!pWindowNeeded()) {
        cb(); 
    } else {
        // The lower the number, the faster the feedback, but the more
        // you hog the system
        setTimeout(callbackWhenWindowNotNeeded, 100);
    }
}

function alertWindow() {
    var w = window.open('','',' width = 200, height = 200, top = 250 , left = 500 ');
    w.document.write("Please Wait<br> Creating Document(s).<br><img src='loadingimage.gif'>");
    w.focus();

    callBackWhenWindowNotNeeded(function() {
        w.close();
    });
}

理想情况下,您可以使用某种MessageBus来阻止轮询。这是一个穷人公共汽车的例子。

var MessageBus = (function(){
   var listeners = [];
   return {
    subscribe: function(cb) {
        listeners.push(cb);
    },
    fire: function(message) {
        listeners.forEach(function(listener){
            listener.call(window);
        });
    }
})();

function alertWindow() {
    var w = window.open('','',' width = 200, height = 200, top = 250 , left = 500 ');
    w.document.write("Please Wait<br> Creating Document(s).<br><img src='loadingimage.gif'>");
    w.focus();

    MessageBus.subscribe(function(message, event) {
        if (message == 'WINDOW_NOT_NEEDED') {
            w.close();
        }
    });
}

// Then wherever you set your newPWindowNeeded
newPWindowNeeded = 'N';
MessageBus.fire('WINDOW_NOT_NEEDED');