1

This code is working fine , but I need to add something in timeout function before return in firstFunction()

function LastFunction(){    
    var answer = firstFunction();   
    console.log(answer) 
}

function firstFunction() {
    //Do something;  
    return somevalue 
}

How to add timeout function inside function before return value ?

function firstFunction() {
    setTimeout (function(){
       var something = "something here"
    },1000)
    return something 
}
4
  • specify 'add somthing to timeout function' Commented Nov 22, 2020 at 19:59
  • just print string now Commented Nov 22, 2020 at 20:02
  • 1
    Are you just asking for a sleep()? Commented Nov 22, 2020 at 20:05
  • 1
    What you are looking for is Promise. What you're asking for does not exist. Commented Nov 22, 2020 at 22:39

1 Answer 1

3

You'll need to use Promises. Your code inside the setTimeout will be delayed but everything outside of it will continue to run synchronously.

function LastFunction(){    
  firstFunction().then(function(val) {
    console.log(val) 
    return val
  })
}

function firstFunction() {
  var promise = new Promise(function(resolve, reject) {
    setTimeout(function(){
        var something = "something here"
        resolve(something)
    },1000)
  })
  return promise
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks , You mentioned it synchronously so could you please add option with asynchronously way ? @Mathew
This is asynchronous. Javascript is synchronous but when you call setTimeout you're scheduling the function you pass in to be called a later time. To get the value, you can use promises which are also asynchronous to wait for the promise to resolve. Then by use .then you can access that value.

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.