code>为超过 500毫秒,则 b 设置为1 当 a 从1更改为0时 - b 设置为0 立即 如果有办法使用函数对此进行编码,那么可以将其附加到变量 a setter?解决方案如果可以,请用 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; } }); 然后,您可以像这样使用它: //立即设置为0 obj.a = 0; console.log(obj.b); //设置为1并开始超时 obj.a = 1; console.log(obj.b); setTimeout(function(){ console.log(obj.b); //设置回0 obj.a = 0; console.log(obj.b); //嘿,确保更改止损b设置为 obj.a = 1; obj.a = 2; setTimeout(function(){ console.log(obj.b); },500); },500); 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 a changes from 0 to 1 - if a is 1 for more than 500ms then b is set to 1When a changes from 1 to 0 - b is set to 0 immediatelyIf there's a way to code this using a function then could that be attached to the variable a's setter ? 解决方案 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 0obj.a = 0;console.log(obj.b);// Set to 1 and start the timeoutobj.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); 这篇关于我可以根据对另一个变量的更改来设置变量的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-26 13:13