简体   繁体   中英

How to break while loop either with timeout or condition is fullfiled?

I want to create a while loop where it will break, whenever timeout finish or condition is fulfilled

async checkFile (filePath) {
    const readDir =  fs.readdirSync(filePath,'utf-8')
    while(true) {
        if(readDir === filename) {
            break;
        }
        
    } 
}

How about something like this? Creating a start date var, then having the condition to loop be that the current date - the start date is less than 1000 (ms) or whatever timeout you would prefer

async checkFile(filePath) {
    const readDir =  fs.readdirSync(filePath,'utf-8');
    const start = new Date();
    while ((new Date()) - start < 1000) {
        if(readDir === filename) {
            break;
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM