Skip to content

Commit 11414f0

Browse files
committed
2nd day
1 parent 902c961 commit 11414f0

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

IntervalCancellation.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Given a function fn, an array of arguments args, and an interval time t, return a cancel function cancelFn.
2+
3+
// After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked.
4+
5+
// setTimeout(cancelFn, cancelTimeMs)
6+
// The function fn should be called with args immediately and then called again every t milliseconds until cancelFn is called at cancelTimeMs ms.
7+
8+
var cancellable = function (fn, args, t) {
9+
fn(...args)
10+
intervalId = setInterval(() => {
11+
fn(...args)
12+
}, t)
13+
cancelFn = () => {
14+
clearInterval(intervalId)
15+
}
16+
return cancelFn
17+
}

Sleep.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,13 @@
11
// Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.
22

3+
/**
4+
* @param {number} millis
5+
* @return {Promise}
6+
*/
7+
async function sleep(millis) {
8+
return await new Promise(res => {
9+
setTimeout(()=>{res()}, millis)
10+
});
11+
}
12+
13+
sleep(100).then(result => console.log(result));

TimeOutCaneccllation.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Given a function fn, an array of arguments args, and a timeout t in milliseconds, return a cancel function cancelFn.
2+
3+
// After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked.
4+
5+
// setTimeout(cancelFn, cancelTimeMs)
6+
// Initially, the execution of the function fn should be delayed by t milliseconds.
7+
8+
// If, before the delay of t milliseconds, the function cancelFn is invoked, it should cancel the delayed execution of fn. Otherwise, if cancelFn is not invoked within the specified delay t, fn should be executed with the provided args as arguments.
9+
10+
11+
/**
12+
* @param {Function} fn
13+
* @param {Array} args
14+
* @param {number} t
15+
* @return {Function}
16+
*/
17+
var cancellable = function (fn, args, t) {
18+
const timeoutId = setTimeout(() => {
19+
fn(...args)
20+
}, t)
21+
const cancelFn = () => {
22+
clearTimeout(timeoutId)
23+
}
24+
return cancelFn;
25+
};

0 commit comments

Comments
 (0)