I have two function like below:
var doSomething = function() {
// first check if user wants to proceed and some other restrictions
checkIfReallyShouldProceed();
console.log('ok, proceed');
// proceed and do something
}
var checkIfReallyShouldProceed = function() {
var check = confirm('really proceed?');
if(!check){
//stop executing doSomething
}
}
doSomething();
If the user does not confirm I want to return from doSomething. Of course I could return the result of the check variable to doSomething and have something like
if(!checkIfReallyShouldProceed()){
return;
}
there, but I want the called function to stop the calling function from executing. Is this possible and if so, how?
An if condition is made for this type of conditional procedure:
var doSomething = function() {
if (checkIfReallyShouldProceed()){
return true; // This will stop the doSomething function from executing
}
console.log('ok, proceed');
}
var checkIfReallyShouldProceed = function() {
return confirm('really proceed?'); // returns true/false
}
doSomething();
In the checkIfReallyShouldProceed function, return whether or not the user wants to proceed. In doSomething, it will stop executing if the called method returns true
Related
I'm sorry if this is a horrible question, I'm a beginner to JS.
So what I'm trying to do is have a function that runs right away and then that function will run other functions if a certain thing is true.
But, when I run it, it says that the function is not yet defined and I can't figure out how to solve this problem. I thank you for your time.
function start() {
var start = prompt('Yes or no?');
if (start === 'Yes') {
yes();
}
but because its in the beginning the functions it runs are below it and are not able to run.
//declare a function called yes
var yes = function(){
alert('You said yes');
};
function start() {
var start = prompt('Yes or no?');
if (start === 'Yes') {
yes();
}
}
start(); //call first function
Passing function as a parameter example.
var fun1 = function(callback) {
var res = prompt('Your ans please');
callback(res);//pass response to function.
};
var handleRes = function(res){
if (res==='yes'){
alert('you said yes');
}
else if(res==='no'){
alert('you said no');
}
else {
alert('you did not say yes or no');
}
};
//call fun1 pass handleRes function to it for callback
fun1(handleRes);
Order in which you write your function matters in JavaScript in some scenarios. Probably the function you are calling is written below it.
Is possible to break execution program from function or I need to check boolean val returned?
Code
function check(something) {
if (!something) return;
// Else pass and program continuing
}
check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..
alert("hello");
One way would be to through an Error, but otherwise you would need to use a boolean check, yes. I would recommend to use the boolean
function check(something) {
if (!something) throw "";
// Else pass and program continuing
}
check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..
alert("hello");
Easiest...
(function(){
function check(something) {
if (!something) return false;
// Else pass and program continuing
}
if(!check(false)) return;
alert("hello");
});
(function(){ ... }); is called IIFE Immediately-invoked function expression.
Put your code in an IIFE, then you can use return
(function() {
function check(something) {
if (!something) {
return false;
} else {
return true;
}
}
if (!check(false)) {
return;
}
alert("hello");
});
Here in result() method, whenever it comes to else part, I need to get out of the function callthis().
It should not execute kumar() function.
Is this possible?
Actually, I can use like this
if(result) //if this method is true, it will come inside
{
kumar();
}
But this is not I want. while returning false from result() method, it should get out of the loop function calthis()
function calthis()
{
var i=1;
if(i==0)
{
alert("inside if");
}
else
{
alert("inside else");
result();
kumar();
}
}
function result()
{
var res = confirm("are you wish to continue");
if(res==true)
{
return true;
alert("inside if result");
}
else
{
return false;
}
}
function kumar()
{
alert("inside kumar");
}
Click here
There's a bunch wrong here.
First, if (result) just tests whether the variable result contains a truthy value, it doesn't actually invoke the function. If you want to test the return value of the function, you need
if (result()) {
Secondly, you're not understanding that return immediately leaves the current function. You can't meaningfully do this:
if(res==true)
{
return true;
alert("inside if result");
}
That alert cannot be reached. The function returns immediately when return true is encountered.
Thirdly, to exit callThis early, you simply need to return early. It's up to the function callThis to conditionally return; you cannot force a return from down inside the result function. A function cannot forcibly return out if the context that called it. It's not up to the internals of the result function to determine if kumar should run. You cannot influence the path of execution in the calling method directly. All result can do is return something, or (needlessly complex in this case) accept a callback and conditionally execute it.
Just return from callThis if the result of result() is false:
function calthis()
{
var i=1;
if(i==0)
{
alert("inside if");
}
else
{
alert("inside else");
if (!result()) return;
kumar();
}
}
To exit any function simply use return;
However it seems like you want to call a function if the user clicks confirm, is that correct? If so:
var res = confirm("are you wish to continue");
if (res === true)
{
kumar();
}
If you want to call a function if the user does not click confirm:
var res = confirm("are you wish to continue");
if (!res)
{
kumar();
}
You got a lot of confusing code going on there, but if the idea is to stop a function, simply use "return false;" and the code execution stops
How can I call the function only for once?
var myFunction = function () {
alert("calling function only for once");
}
myFunction();//alert "calling function only for once"
myFunction();//should not alert // if I call multiple times this should not be called
Try this:
var myFunction = function () {
alert("calling function only for once");
myFunction = function(){
return false;
}
}
myFunction();//alert "calling function only for once"
myFunction();//should not alert
Store some goobal variable a flag when run the function and check that variable at the start of the function.
set a flag, and call according to that flag:
var IsAlreadyCalled=false;
var myFunction = function () {
if(!IsAlreadyCalled){
alert("calling function only for once");
IsAlreadyCalled = true;
}
}
myFunction();//alert "calling function only for once"
myFunction();//should not alert
In your very odd scenario , the easiest way is to set a boolean:
var run = true,
myFunction = function(){
if(run){
alert('calling function only for once');
run = false;
} else {
return false;
}
};
myFunction(); // will run
myFunction(); // won't run
That way later on if you need to "reactivate" it you can just set the boolean back to true and call it again.
run = true;
myFunction(); // will run again
Other suggestions of using a flag are fine, but I would build it as a function decorator, that you can apply to any function. You avoid global variables this way, and your code becomes more readable and reusable:
// Takes a function and returns a function
// that executes only once
function once(f) {
var flag;
return function() {
if (!flag) {
flag = true;
return f.apply(this, arguments);
}
};
}
var fn = once(function() {
console.log('logged!');
});
fn(); // logged!
fn();
fn();
Demo: http://jsbin.com/povu/1/edit
I am looking for a good technique to get away from what I am tempted to do: to set a global variable.
The first time someone runs a function by clicking a button it triggers an initial function to turn a few things into draggables. Later, if they click the button a second time I want to determine if the init function has been initialized, and if so to not call it again. I could easily do this by setting a global variable from the init function and then checking that variable from the click function, but I'm wondering how to do this without setting a global variable. I would really like an example of a way to do this.
You could add a property to the function:
function init() {
init.called = true;
}
init();
if(init.called) {
//stuff
}
While #Levi's answer ought to work just fine, I would like to present another option. You would over write the init function to do nothing once it has been called.
var init = function () {
// do the initializing
init = function() {
return false;
}
};
The function when called the first time will do the init. It will then immediately overwrite itself to return false the next time its called. The second time the function is called, the function body will only contain return false.
For more reading: http://www.ericfeminella.com/blog/2011/11/19/function-overwriting-in-javascript/
Why don't you just check to see if your draggables have a class of draggable on them?
if ($('.mydiv').is('.draggable')) {
//do something
}
Function.prototype.fired = false;
function myfunc() {
myfunc.fired = true;
// your stuff
};
console.log(myfunc.fired) // false
myfunc();
console.log(myfunc.fired) // true
What you could do is unhook the init function from the prototype.
var Obj = function () {
this.init = function () {
document.write("init called<br/>");
this.init = null;
}
}
var o = new Obj();
if (o.init) document.write("exists!<br/>");
o.init();
if (o.init) document.write("exists!<br/>");
o.init();
The first if will be true and print exists! but since the function removes itself, the second if will fail. In my example, I call the second init unconditionally just to show that nothing will happen, but of course you could call it only if it exists:
if (o.init) o.init();
http://jsfiddle.net/coreyog/Wd3Q2/
The correct approach is to use the Javascript Proxy APIs to trap the function calls using apply handler.
const initFun = (args) => {
console.log('args', args);
}
const init = new Proxy(initFun, {
apply(target, thisArg, args){
target.calls = target.calls ? target.calls + 1 : 1;
return target.apply(thisArg, args);
}
});
init('hi');
console.log(init.calls); // 1
init('hello');
console.log(init.calls); // 2