多花了一點時間,一開始有被題目嚇到。
Day16: Promise Time Limit
問題描述:
Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function. fn takes arguments provided to the time limited function.
The time limited function should follow these rules:
- If the 
fncompletes within the time limit oftmilliseconds, the time limited function should resolve with the result. - If the execution of the 
fnexceeds the time limit, the time limited function should reject with the string"Time Limit Exceeded". 
問題難度:Medium
問題限制:
0 <= inputs.length <= 100 <= t <= 1000fnreturns a promise
我的解題過程:
之前有寫過基礎的問題,如promise、setTimeout、clearTimeout。
這題感覺時把所有的問題整合,當下看到有點不知所措,但一步步拆解後就又好像不難。
首先題目有說到如果成功要….失敗要…
看起來就很像promise的寫法,因此先創立一個promise
1  | return new Promise((resolve, reject) => {code})  | 
接下來要來處理code的部分,根據題目的需求我們設置一個setTimeout,並且要包含clearTimeout:
1  | const timeoutId = setTimeout(() => {  | 
接下來就是讓fn執行這個setTimeout了
1  | fn(...args)  | 
這邊在一開始我犯了個錯誤,並沒有使用…,想說之前已經把所有參數傳入args了,但第一次使用 ...args 是為了接收所有傳入 timeLimit 的參數,而第二次使用 ...args 則是為了將這些參數傳遞給 **fn**。
完整code
1  | var timeLimit = function (fn, t) {  | 
其他code
1  | var timeLimit = function(fn, t) {  | 
總結
看到問題時真的不能緊張,仔細觀察題目。基本上以我目前的能力所有的解答方式我都有學過了,只要靜下心來一定有辦法解開(拼時間的還不行,現階段能解出來就要偷笑了)。