1

So I have this function which I would like to run:

const normal = () => {
  return 'working
}

I can log its output and it works fine:

console.log(normal()) // does output: 'working'

Now I would like to run a function delayed which is exactly the same as normal only it takes 3 seconds before returning

I would like to be able to log this function call but only after 3 seconds, I am understandably logging undefined at the moment and have a feeling that it might be possible to do. Anyway I want the following to happen, the function to hang for 3 seconds, then return data:

console.log(delayed()) // should output: 'working'

My attempts:

const toReturn = () => {
  return 'working'
}

const runner = (cb) => {
  setTimeout(cb, 1000)
}

export const delayed = () => {
  return runner(toReturn)
}

console.log(delayed()) // currently outputting: undefined

undefined is because I am not returning anything from runner, if I return setTimout... in runner, I simply get the whole setTimout function, which is pretty useless.

I know you can simply log after 3 seconds within a callback, but I would like to log what is returned from a setTimeout

Sam Houston
  • 3,413
  • 2
  • 30
  • 46
  • 2
    You mean, lock the users' browser for 3 seconds? Sure you can do it! But don't expect any positive feedback. This will make the system unresponsive and destroy your users' work. – Ismael Miguel Apr 20 '16 at 21:48

1 Answers1

1

When you call console.log (or anything else) it's going to take that action then. JS is not like some languages where you pause code execution.

If you want the console.log to be delayed then you need to delay the actual call to console.log, not the return of the value you're logging.

The simplest way would be something like this:

function delayedLog(seconds)
{
    setTimeout(function(){
        var val = getSomething(); // <- pretend this returns "later"
        console.log(val); // <- after 3 seconds logs "later"
    }, seconds*1000);
}

console.log('now');
delayedLog(3);
BryanGrezeszak
  • 577
  • 2
  • 8