0

I have to call a function with the callback in set timeout for that I have written code like this

getData(a, b, function(err, rlt) {
    if (err) {
        console.log(err)
    } else {
        // call next function after 35 seconds 
        settimeout(getData(c, d, function(err, rlt) {
            if (err) {
                console.log(err)
            } else {
                // call next function after 10 seconds
                settimeout(getData(x, y, function(err, rlt) {
                    if (err) {
                        console.log(err)
                    } else {
                        console.log(rlt);
                    }
                }), 10000);
            }
        }), 35000)
    }
});


function getData(parms1, parms2;, callback) {
    return callback(null, parms1 + parms2);
}

I have written code similar to this but my problem is that set timeout not working its execute function immediately not wait for 35 seconds and 10 seconds.

I don't know what wrong I am doing and if you know any better way to do please help me.

4
  • function getData(parms1, parms2;, callback) { return parms1 + parms2; } is this correct? Commented Jul 19, 2018 at 3:34
  • @NullPointer sorry my bad i forgot to put callback over there i just updated my question Commented Jul 19, 2018 at 3:37
  • 1
    Just curious... have you considered using Promise or async await instead of setTimeout? The code you have shared is fragile and a good example of callback hell. Commented Jul 19, 2018 at 3:40
  • I know to do all these thing with async but it want to execute other function after sometime not immediately Commented Jul 19, 2018 at 3:44

3 Answers 3

1

You must wrap your calls to getData in an anonymous function, e.g. setTimeout(function(){ getData(x, y, …) }, 1000).

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

2 Comments

thax its worked..but if konw better way please tell me i want to avoid this callback hell
1

Below is the correct syntax for setTimeout.Your method should be always as a first argument of setTimeout function

setTimeout(function(){myMethod(parameter);},3000);

Full Reference: http://www.java2s.com/Tutorials/Javascript/Node.js_Tutorial/0270__Node.js_setTimeout_setInterval.htm

1 Comment

thax its worked..but if konw better way please tell me i want to avoid this callback hell
0

I think you miss spell of settimeout(setTimeout) Try this code:

 var callback = function (err, res) {
        if(err){
           console.log (err);
        }else{
              setTimeout(function() {
                 callback()
                 console.log ("start callback function");
                 }, 10000)
        }
    };

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.