0

How can I make my function not to repeat the multiple calls, if multiple calls were made in mins?

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);

I am expecting the result -

done 
no more repeat calling
2
  • check on x not on s Commented Oct 25, 2017 at 14:02
  • Rubber Duck Debug your code. Commented Oct 25, 2017 at 14:03

2 Answers 2

3

Because s is never being set to 2. It looks like you meant to do that in the if block, rather than the else block:

if (s === 1) {
    console.log('done');
    s = 2;  // <--- here
    setTimeout(function(){
        s = 1; 
    }, 10000);
} else {
    console.log('no more repeat calling');
}

That way the first call will update the s flag, so subsequent calls will go to the else block.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

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);

1 Comment

It will be better, if we explain our answer. Not just a code block. Right ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.