如何使程序等待javascript中的变量?

Tha*_*sas 60 javascript variables wait

我想强制JavaScript程序在其执行的某些特定点等待,直到变量发生变化.有办法吗?我已经找到了一个名为"叙事JavaScript"的扩展,它强制程序等到事件发生.有没有办法创建一个新事件,例如一个"变量事件",其行为类似于onclick事件.

aul*_*ron 87

编辑2018:请查看Object getters and settersProxies.老答案如下:


一个快速简单的解决方案是这样的:

var something=999;
var something_cachedValue=something;

function doStuff() {
    if(something===something_cachedValue) {//we want it to match
        setTimeout(doStuff, 50);//wait 50 millisecnds then recheck
        return;
    }
    something_cachedValue=something;
    //real action
}

doStuff();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢大家的答案!但在所有解决方案中,程序都不会阻塞!它将继续正常执行,如果在执行期间变量发生变化,则将调用回调。但是,我想要做的是强制程序阻止其执行,直到变量更改(通过调用函数),然后从被阻止的这一点继续!有任何想法吗? (2认同)

Reb*_*oot 21

JavaScript解释器是单线程的,因此当代码在一些其他不改变变量的代码中等待时,变量永远不会改变.

在我看来,将变量包装在某种具有getter和setter函数的对象中是最好的解决方案.然后,您可以在调用对象的setter函数时在调用的对象中注册回调函数.然后,您可以在回调中使用getter函数来检索当前值:

function Wrapper(callback) {
    var value;
    this.set = function(v) {
        value = v;
        callback(this);
    }
    this.get = function() {
        return value;
    }  
}
Run Code Online (Sandbox Code Playgroud)

这可以很容易地使用:

<html>
<head>
<script type="text/javascript" src="wrapper.js"></script>
<script type="text/javascript">
function callback(wrapper) {
    alert("Value is now: " + wrapper.get());
}

wrapper = new Wrapper(callback);
</script>
</head>
<body>
    <input type="text" onchange="wrapper.set(this.value)"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 如果你能控制原始变量,可能是最好的解决方案. (2认同)

Cip*_*ipi 5

我会推荐一个能够处理更改值的包装器.例如,您可以使用JavaScript函数,如下所示:

?function Variable(initVal, onChange)
{
    this.val = initVal;          //Value to be stored in this object
    this.onChange = onChange;    //OnChange handler

    //This method returns stored value
    this.GetValue = function()  
    {
        return this.val;
    }

    //This method changes the value and calls the given handler       
    this.SetValue = function(value)
    {
        this.val = value;
        this.onChange();
    }


}
Run Code Online (Sandbox Code Playgroud)

然后你可以创建一个可以保存你想要监视的值的对象,以及一个在值发生变化时调用的函数.例如,如果您希望在值更改时收到警报,并且初始值为10,则可以编写如下代码:

var myVar = new Variable(10, function(){alert("Value changed!");});
Run Code Online (Sandbox Code Playgroud)

function(){alert("Value changed!");}调用时将调用处理程序(如果查看代码)SetValue().

你可以得到这样的价值:

alert(myVar.GetValue());
Run Code Online (Sandbox Code Playgroud)

您可以像这样设置值:

myVar.SetValue(12);
Run Code Online (Sandbox Code Playgroud)

紧接着,屏幕上会显示警报.看看它是如何工作的:http://jsfiddle.net/cDJsB/


Mik*_*ier -4

不,您必须创建自己的解决方案。比如使用观察者设计模式之类的。

如果你无法控制变量或谁在使用它,恐怕你就完蛋了。编辑:或者使用 Skilldrick 的解决方案!

麦克风