如果在分钟内进行多次通话,如何让我的功能不重复多次通话?
var s = 1;
function foo(x) {
if (s === 1) {
console.log('done');
setTimeout(function(){
s =1;
}, 10000);
} else {
s = 2;
console.log('no more repeat calling');
}
}
foo(1);
foo(2);
我期待结果 -
done
no more repeat calling
答案 0 :(得分:3)
因为s
永远不会被设置为2
。您似乎打算在 if 块中执行此操作,而不是 else 块:
if (s === 1) {
console.log('done');
s = 2; // <--- here
setTimeout(function(){
s = 1;
}, 10000);
} else {
console.log('no more repeat calling');
}
这样第一个调用将更新s
标志,因此后续调用将转到else
块。
答案 1 :(得分:0)
试试这个:
var s = 1;
function foo(x) {
if (s === 1) {
s = 0;
console.log('done');
setTimeout(function(){
s = 1;
}, 10000);
} else {
console.log('no more repeat calling');
}
}
foo(1); foo(2);foo(3);
&#13;