|
1 | 1 | ## Run to completion
|
2 | 2 |
|
3 |
| -### 1. Let's have a look to the code that we have in `main.js` |
| 3 | +### 1. Let's creae code that will be blocking in some pint. |
| 4 | + |
| 5 | +```javascript |
| 6 | +document.onreadystatechange = () => { |
| 7 | + if(document.readyState === 'complete') { |
| 8 | + const btn = document.getElementById("button"); |
| 9 | + btn.addEventListener('click', (evt) => { |
| 10 | + evt.stopPropagation(); |
| 11 | + // modify page |
| 12 | + document.body.style.backgroundColor = 'lime'; |
| 13 | + let p = document.createElement("p"); |
| 14 | + p.innerText = "let's add some text to the page"; |
| 15 | + document.body.appendChild(p); |
| 16 | + |
| 17 | + // simulate blocking / long running operation |
| 18 | + const start = Date.now(); |
| 19 | + const delaySeconds = 10; |
| 20 | + while (Date.now() < start + delaySeconds * 1000) {} |
| 21 | + }); |
| 22 | + } |
| 23 | +}; |
| 24 | +``` |
| 25 | + |
| 26 | +### 2. To have a little bit of better understanding lets refactor a bit |
| 27 | + |
| 28 | +```diff |
| 29 | +document.onreadystatechange = () => { |
| 30 | + if(document.readyState === 'complete') { |
| 31 | + const btn = document.getElementById("button"); |
| 32 | + btn.addEventListener('click', (evt) => { |
| 33 | + evt.stopPropagation(); |
| 34 | +- // modify page |
| 35 | +- document.body.style.backgroundColor = 'lime'; |
| 36 | +- let p = document.createElement("p"); |
| 37 | +- p.innerText = "let's add some text to the page"; |
| 38 | +- document.body.appendChild(p); |
| 39 | +- |
| 40 | +- // simulate blocking / long running operation |
| 41 | +- const start = Date.now(); |
| 42 | +- const delaySeconds = 10; |
| 43 | +- while (Date.now() < start + delaySeconds * 1000) {} |
| 44 | ++ modifyPage(); |
| 45 | ++ blockingOperation(); |
| 46 | + }); |
| 47 | + |
| 48 | ++ const modifyPage = () => { |
| 49 | ++ // modify page |
| 50 | ++ document.body.style.backgroundColor = 'lime'; |
| 51 | ++ let p = document.createElement("p"); |
| 52 | ++ p.innerText = "let's add some text to the page"; |
| 53 | ++ document.body.appendChild(p); |
| 54 | ++ }; |
| 55 | ++ |
| 56 | ++ const blockingOperation = () => { |
| 57 | ++ // simulate blocking / long running operation |
| 58 | ++ const start = Date.now(); |
| 59 | ++ const delaySeconds = 10; |
| 60 | ++ while (Date.now() < start + delaySeconds * 1000) {} |
| 61 | ++ } |
| 62 | + } |
| 63 | +}; |
| 64 | +``` |
| 65 | + |
| 66 | +### 3. Let's have a look to the code that we have in `main.js` |
4 | 67 |
|
5 | 68 | ```javascript
|
6 | 69 | btn.addEventListener('click', (evt) => {
|
|
0 commit comments