问题
I have a javascript variable a and a variable b that can have a value of 0 or 1.
Can anyone suggest how I could code a function sob could depend on the value of a like this:
- When
achanges from 0 to 1 - ifais 1 for more than 500ms thenbis set to 1 - When
achanges from 1 to 0 -bis set to 0 immediately
If there's a way to code this using a function then could that be attached to the variable a's setter ?
回答1:
If you can, wrap the access with defineProperty:
var obj = {
_a: 1
};
Object.defineProperty(obj, "a", {
get: function() {
return this._a;
},
set: function(newA) {
if (this.changeB) {
clearTimeout(this.changeB);
this.changeB = null;
}
if (this.a == 0 && newA == 1) {
this.changeB = setTimeout(function() {
this.b = 1;
}.bind(this), 500);
}
else if (this.a == 1 && newA == 0) {
this.b = 0;
}
this._a = newA;
}
});
Then, you can use it like so:
// Immediately set to 0
obj.a = 0;
console.log(obj.b);
// Set to 1 and start the timeout
obj.a = 1;
console.log(obj.b);
setTimeout(function() {
console.log(obj.b);
// Set back to 0
obj.a = 0;
console.log(obj.b);
// And hey, make sure changing a stops b from being set
obj.a = 1;
obj.a = 2;
setTimeout(function() {
console.log(obj.b);
}, 500);
}, 500);
回答2:
This is how I'd do it, just define a toggleA function that has access to the outer scope:
var a = 0, b, t,
toggleA = function() {
switch(a) {
case 0:
a = 1;
t = window.setTimeout(function(){ b = 1; }, 500);
break;
case 1:
window.clearTimeout(t);
a = b = 0;
break;
}
};
Calling toggleA() will switch as value between 1 and 0. Depending on how long it takes to switch the value of a from 1 to 0, the value of b may also be changed.
来源:https://stackoverflow.com/questions/23692174/can-i-make-a-variables-value-depend-on-changes-to-another-variable