How To Call A Function Inside Same Function And Outside In Javascript
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 += '
Solution 1:
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 somewhereconsole.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 );
Solution 2:
I guess you want to implement it using recursion, this might help you.Change you condition and output in code as you expect.
functionsomeFunction(result) {
document.body.innerHTML += '<br>' + result;
result--;
if (result===0) {
return;
}
returnsomeFunction(result);
}
someFunction(5);
Post a Comment for "How To Call A Function Inside Same Function And Outside In Javascript"