make sure a solution always shows up, use "demo" if exists
This commit is contained in:
parent
360be9ed99
commit
408ba7d4e4
25 changed files with 59 additions and 95 deletions
|
@ -1,6 +1,6 @@
|
|||
The solution:
|
||||
|
||||
```js
|
||||
```js run demo
|
||||
function delay(f, ms) {
|
||||
|
||||
return function() {
|
||||
|
@ -8,20 +8,25 @@ function delay(f, ms) {
|
|||
};
|
||||
|
||||
}
|
||||
|
||||
let f1000 = delay(alert, 1000);
|
||||
|
||||
f1000("test"); // shows "test" after 1000ms
|
||||
```
|
||||
|
||||
Please note how an arrow function is used here. As we know, arrow functions do not have own `this` and `arguments`, so `f.apply(this, arguments)` takes `this` and `arguments` from the wrapper.
|
||||
|
||||
If we pass a regular function, `setTimeout` would call it without arguments and `this=window` (in-browser), so we'd need to write a bit more code to pass them from the wrapper:
|
||||
If we pass a regular function, `setTimeout` would call it without arguments and `this=window` (assuming we're in the browser).
|
||||
|
||||
We still can pass the right `this` by using an intermediate variable, but that's a little bit more cumbersome:
|
||||
|
||||
```js
|
||||
function delay(f, ms) {
|
||||
|
||||
// added variables to pass this and arguments from the wrapper inside setTimeout
|
||||
return function(...args) {
|
||||
let savedThis = this;
|
||||
let savedThis = this; // store this into an intermediate variable
|
||||
setTimeout(function() {
|
||||
f.apply(savedThis, args);
|
||||
f.apply(savedThis, args); // use it here
|
||||
}, ms);
|
||||
};
|
||||
|
||||
|
|
|
@ -1,6 +1,4 @@
|
|||
|
||||
|
||||
```js run no-beautify
|
||||
```js demo
|
||||
function debounce(f, ms) {
|
||||
|
||||
let isCooldown = false;
|
||||
|
@ -18,7 +16,7 @@ function debounce(f, ms) {
|
|||
}
|
||||
```
|
||||
|
||||
The call to `debounce` returns a wrapper. There may be two states:
|
||||
A call to `debounce` returns a wrapper. There may be two states:
|
||||
|
||||
- `isCooldown = false` -- ready to run.
|
||||
- `isCooldown = true` -- waiting for the timeout.
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
```js
|
||||
```js demo
|
||||
function throttle(func, ms) {
|
||||
|
||||
let isThrottled = false,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue