0

I saw many examples of timer with Promise for JavaScript. Most of them are too complicated, but I suppose, it could be implemented more simply. However, I need the solution for TypeScript in "strict": true mode with all annotations.

I tried to do it until below code:

import Timeout = NodeJS.Timeout;

let testTimeout : Timeout;
const DELAY: number = 3000;

testTimeout = (): Promise<void> => (
  new Promise<void>( (resolve): void => {
    setTimeout(resolve, DELAY);
  })
);

testTimeout = testTimeout().then( () => {
  console.log('done');
});
clearTimeout(testTimeout);

It has errors:

TS2739: Type '() => Promise<void>' is missing the following properties from type 'Timeout': ref, refresh, unref

TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'Timeout' has no compatible call signatures.

I suppose, I do something wrong.

Takeshi Tokugawa YD
  • 670
  • 5
  • 40
  • 124

1 Answers1

-1

Try this:

function setTimeoutPromise(fn: () => number, delay: number): Promise<number> {
    return new Promise( (resolve, reject) => {
        setTimeout(() => {
            resolve(fn())
        }, delay)
    })
}

setTimeoutPromise(() => {
    console.log('resolving...');
    return 10;
}, 5000).then((res) => console.log('should print 10 after 5 secs', res));

this compiles fine with tsc --strict true. I am not sure if this what you are looking for though. Let me know!

There is another way of achieving this that I have just thought about:

import * as util from 'util';

const setTimeoutPromise = util.promisify((delay, fn) => setTimeout(fn, delay));
setTimeoutPromise(5000).then(() => console.log('hey you!'));

It might look a bit strange but it works. Basically .promisify expects a standard callback-last function to be passed to it as an argument where as the setTimeout has the opposite signature. So we reverse them:)

MrfksIV
  • 900
  • 6
  • 16
  • Thank you for the answer! Unfortunately, I did not understand from the first example, how to do `clearTimeout()`. – Takeshi Tokugawa YD Apr 08 '19 at 06:53
  • This is not a complete answer. Please add how to use clearTimeout or remove it. The standard setTimout as promise has been answered somewhere else. https://stackoverflow.com/questions/22707475/how-to-make-a-promise-from-settimeout – Split Your Infinity Oct 05 '19 at 08:32