Created
August 14, 2020 08:40
-
-
Save bankchart/f664affc51c4e8924a0829e88ba0d76a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| input text search server side processing เมื่อมีการกรอกข้อมูลใดๆ ให้ทำการ | |
| call api โดยการแนบข้อมูลทั้งหมดจากใน text นั้นไปเสมอ | |
| condition: | |
| - หลังจากกรอกตัวอักษรใดๆ เสร็จสิ้นแล้ว เมื่อเวลาผ่านไป 500ms ให้ทำการ call api | |
| - ระยะเวลาระหว่างการกรอกข้อมูลแต่ละตัวอักษรน้อยกว่า 500ms ห้าม call api | |
| - ในกรณีที่ call api ไปแล้วเกิดการกรอกตัวอักษรใดๆ ให้ทำการยกเลิก request | |
| ก่อนหน้าทุกครั้งเสมอ ต้องไม่ได้ผลลัพธ์ใดๆ กลับมาเพราะทำการยกเลิก request แล้ว | |
| *หมายเหตุ: ใช้ promise ในการ mock api และ random response time ใหม่ทุกครั้งที่ call | |
| *เกียวกับการจัดการ process ที่เป็น non-blocking | |
| เฉลย | |
| ==================================== script ==================================== | |
| const searchTextElm = document.getElementById('search-text'); | |
| const intervalTime = 500; | |
| let timer = null; | |
| let keyupTime = null; | |
| let token = {}; | |
| searchTextElm.addEventListener("keyup", (event) => { | |
| keyupTime = new Date(); | |
| if (timer) { | |
| clearTimeout(timer); | |
| } | |
| timer = triggerCallApi(); | |
| }); | |
| const randomResponseTime = (textVal, token = {}) => { | |
| return new Promise((resolve, reject) => { // mock response | |
| const responseTime = Math.floor(Math.random() * 10000) + 1; | |
| token.cancel = () => { | |
| reject(new Error('cancel request=' + textVal)); | |
| }; | |
| setTimeout(() => { | |
| resolve('ok, responseText=' + textVal); | |
| }, responseTime); | |
| }); | |
| }; | |
| const triggerCallApi = () => { | |
| if (timer && token.cancel) { | |
| token.cancel(); | |
| } | |
| return setTimeout(() => { | |
| const startCallTime = new Date(); | |
| const shouldBeCallApi = startCallTime - keyupTime >= intervalTime; | |
| if (shouldBeCallApi) { | |
| console.log('start search=', searchTextElm.value); | |
| randomResponseTime(searchTextElm.value, token).then((resp) => { | |
| console.log('responseText=' + resp); | |
| }) | |
| .catch((err) => console.error(err)); | |
| } | |
| }, intervalTime); | |
| }; | |
| ==================================== html ==================================== | |
| <input id="search-text" type="text"/> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment