samedi 27 octobre 2018

Try and catch in javascript are not working properly

Here I made a custom setInterval function but it is not working as desired.

function interval(func,ti,f){
if(f==0||f==undefined){
    try{                  //calls the function provided as argument.
        func.call();
    }
    catch(err){            //if error occurs
        alert('error occured!'); //edited       
        throw new Error("error occured!!");//edited

    }
    setTimeout(interval(func,ti,f),ti);
   }
}

the main idea behind this is that the user calls the function somewhat like this:

interval(()=>{
   console.log('hello world');
 }, 10000,0);

Since f=0 so it satisfies and enters the if statement. now when try{} calls the function, it executes.

the problem is whenever I am passing the function something like this:

    interval(()=>{
      console.log(x);
    },10000);

here x is not defined so it should go to catch and show alert and then error and at last stop execution. The problem is that it is showing error but not the one which I want to display i.e error occurred plus it is not displaying the alert. Probably it's not entering the catch(){} part of the code.

Plz, help me in figuring out the problem.




Aucun commentaire:

Enregistrer un commentaire