确定布尔值何时从真变为假

Determine when a boolean changes from true to false

本文关键字:布尔值 何时      更新时间:2023-09-26

我有一个网页,有一个打印按钮。只要按下打印按钮,我就有一个功能

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

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

一切正常

当用户点击打印窗口时这个函数正在运行

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时,最有效的评估方法是什么?

谢谢

效率最低但最简单的方法是使用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');