Promise Timeout Wrapper
JavaScript
Hard
5 views
Problem Description
Given duration t and timeout ms. Simulate a promise that resolves after t ms. If it does not finish within timeout, print TIMEOUT else DONE.
Input Format
One line: t timeout.
Output Format
TIMEOUT or DONE.
Official Solution
const fs=require('fs');const [t,timeout]=fs.readFileSync(0,'utf8').trim().split(/\\s+/).map(Number);const work=()=>new Promise(res=>setTimeout(res,t));const withTimeout=(p,ms)=>Promise.race([p.then(()=>true),new Promise(res=>setTimeout(()=>res(false),ms))]);(async()=>{const ok=await withTimeout(work(),timeout);process.stdout.write(ok?'DONE':'TIMEOUT');})();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!