Self-Study/Javascript
[Javascript] polling
Raadian
2022. 7. 4. 11:29
References
https://junhyunny.github.io/information/javascript/polling-long-polling-and-javascript-example/
https://junhyunny.github.io/information/spring-boot/polling-long-polling-and-spring-example/
폴링(Polling)의 정의
클라이언트 측에서 일정 주기로 서버에게 필요한 데이터를 요청하는 방식.
Polling 구현
setTimeout(callback, timeout) 사용
callback 함수 실행 시간과 상관없이 callback 함수 실행 간격이 일정하게 보장된다.
export const timeoutPolling = (func, timeout, maxAttempts = -1) => {
if (maxAttempts === 0) {
return;
}
setTimeout(async () => {
try {
await func();
} catch (error) {
console.error(error);
}
timeoutPolling(func, timeout, maxAttempts - 1);
}, timeout);
};
setInterval(callback, timeout) 사용
callback 함수 실행 시간이 길어지면 callback 함수 실행 간격이 짧아진다.
export const intervalPolling = (func, interval, maxAttempts = -1) => {
let attempts = 0;
let intervalId = setInterval(() => {
if (maxAttempts === attempts) {
clearInterval(intervalId);
return;
}
attempts++;
func();
}, interval);
};
sleep(timeout) 사용
시간 간격을 만들 수 있는 형태로 sleep을 사용한다. 그러나 javascript에서는 sleep 내장 함수가 없으므로 사전 정의 후 사용한다.
const sleep = (timeout = 100) => {
// Promise와 setTimeout을 이용하여 sleep 함수를 구현한다
return new Promise(resolve => {
setTimeout(resolve, timeout);
});
}
export const sleepPolling = async (func, validateFunc, timeout) => {
let result = await func();
while (!validateFunc(result)) {
await sleep(timeout);
try {
result = await func();
} catch (e) {
console.log(e.message);
}
}
return result;
}