2

I want to call a function inside that same function and outside also. How does it in javascript?

Js:

someFunction(function repeat(result) {
    document.body.innerHTML += '<br>' + result.winner;
    if (result.winner) {
        someFunction(repeat);
    }
});
someFunction.repeat();
8
  • why would you want to do this. .... this creates an endless loop .... Commented Sep 20, 2018 at 11:51
  • I have more if condition..So I will call only with some condition Commented Sep 20, 2018 at 11:52
  • Declare both functions before using them. Either as a variable ( expression ) or as a declaration. Commented Sep 20, 2018 at 11:52
  • Can you edit mycode? Commented Sep 20, 2018 at 11:53
  • output.jsbin.com/bederuyizo See the Console, try something like this Commented Sep 20, 2018 at 11:54

2 Answers 2

2

var someFunction = function( callback ) {
  // Do some things that belong to someFunction, like creating the result object.
  var result = {
    winner: true
  };
  // Call the repeat function, using the result as the parameter.
  callback( result );
};
var endless_loop_protection = 0;
var repeat = function( result ) {
  // Write the result somewhere
  console.log( result.winner + ': ' + endless_loop_protection );
  // faking the if clauses that prevent the endless loop.
  endless_loop_protection += 1;
  if ( result.winner && endless_loop_protection < 10 ) {
    // Do everything again if there's still a winner in the result.
    someFunction( repeat );
  }
};
someFunction( repeat );


Depending on what exactly else is inside the someFunction function and the repeat function, a structure like this could work better:

var get_result = function() {
  // Create a random result.
  return {
    winner: Math.random() < 0.5
  };
};
// This will keep looping until get_result returns a result with winner = true.
// So the amount of times this will log is random each time you call it.
var handle_results_until_winner = function( get_result ) {
  var result = get_result();
  console.log( result.winner );
  if ( !result.winner ) handle_results_until_winner( get_result );
};
handle_results_until_winner( get_result );

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

Comments

1

I guess you want to implement it using recursion, this might help you.Change you condition and output in code as you expect.

function someFunction(result) {
     document.body.innerHTML += '<br>' + result;
     result--;
   
    if (result===0) {
       return;
     }
     
     return someFunction(result);
}
 someFunction(5);

Comments

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.