Search code examples
typescriptreact-nativesleep

setTimeout never ends in typescript


I try to implement a sleep method for a React Native application in Typescript. My implementation is the following:

sleep = (ms:number) => new Promise(r => setTimeout(() => r, ms));

inspired by How to implement sleep function in TypeScript?

And I use it this way in a Component:

getData = async () => {
    this.setState({isLoading: true});
    await this.sleep(1000);
    const res = await getUser("test") ?? new User("", "", "", null, null, 0, 0);
    this.state.isLoading = false;
    this.setState({user : res, isLoading: false});
}

But using break points, I noticed that the code doesn't go further than await this.sleep(1000); and my application stays in loading state. What could be the reason for this ?


Solution

  • instead of

    sleep = (ms:number) => new Promise(r => setTimeout(() => r, ms));
    
    sleep = (ms) => new Promise(r => setTimeout(r, ms));
    // replace `() => r` with `r`
    

    So the problem is, inside setTimeout, instead of execute function r you currently return a function r and setTimeout not using it.

    setTimeout(() => r, ms)
    // same as
    setTimeout(() => {
        // you doing nothing here
        return r; // setTimeout not using this
    }, ms)
    

    Learn more at document of setTimeout at here

    Update:

    • fix: No overload matches this call
    const sleep = (ms: number) => new Promise<void>((resolve) => {
        setTimeout(() => {
            resolve()
        }, ms);
    });