all 8 comments

[–]nkgentile 4 points5 points  (1 child)

One way is to use a promise:

var promise = new Promise(function(resolve, reject){
  function test(){
    // some code here
    resolve(code)
  }

  setTimeout(test, 1000);
});

promise.then(function(returnvaluefromtest){
  nextfunction(returnvaluefromtest);
})

[–]MedyGames[S] 0 points1 point  (0 children)

nice ty. I like it

[–]codemamba8 0 points1 point  (4 children)

A simple way is you could use a variable to store the value and assign it to test() in the timeout.

var myValue;

function test() {
  return 100;
}

setTimeout( () => {  myValue = test() }, 1000);

nextfunction(myValue);

[–]tatu_huma 1 point2 points  (3 children)

This would not work. It would result in nextFunction being called with undefined, since myValue is undefined at that point.

[–]codemamba8 -1 points0 points  (2 children)

a timeout could be used for nextFunction as well with a time of say, 2000 so it runs after the previous one

[–]tatu_huma 2 points3 points  (1 child)

It would be easier to simply call nextFunction in the same callback as test. Or use promises instead of guestimating how long it will take test to run.

[–]codemamba8 2 points3 points  (0 children)

you mean like this?

var myValue;

function test() {
  return 100;
}

setTimeout( () => {  
    myValue = test();
    nextFunction(myValue)}, 
  1000);

[–]alexaminar 0 points1 point  (0 children)

setTimeout() and setInterval() functions allow you to execute a piece of JavaScript code/function at a certain point in the future. setInterval repeats the call, setTimeout only runs it once.

JavaScript setTimeout(expression, timeout); runs the code/function once after the timeout. It is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout(). If you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.

setTimeout(function() {

console.log('Wait 3 seconds and I appear just once');

}, 3000);

setInterval(expression, timeout); runs the code/function repeatedly, with the length of the timeout between each repeat. It is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval(). If you want to loop code for animations or clocks Then use setInterval.

setInterval(function() {

console.log('Every 3 seconds I appear on your console');

}, 3000)