有没有办法可以在if条件下重新加载javascript函数? 例如,说我有一个功能
runCode(){
//do something
}
第一次尝试
setInterval(function(){
runCode();
},1000);
但我不希望它在一段时间内重新加载,但是在if条件下。
让我们说我有一个函数有时会返回true,有时是假的,基于用户在textarea中输入的内容(例如!)。所以在这种情况下,我希望能够在用户输入后检查它是否变为true或反之,如果是,我需要重新加载函数runCode()
答案 0 :(得分:1)
if (expression) {
runcode();
}
答案 1 :(得分:1)
是.. 您可以在if范围内调用该函数。
if(condition){
runCode();
}
答案 2 :(得分:0)
您可以使用setter在更改值后运行函数:
function sayHello(){
alert('hello!');
}
Object.defineProperty(window, 'condVar', {
get: function() {
return this._condVar;
},
set: function(value) {
if(value === 123)
sayHello();
this._condVar = value;
}
});
alert('setting 123');
condVar = 123;
alert('setting abc');
condVar = 'abc';
alert('setting 123');
condVar = 123;
有关setter的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set