투케이2K

561. (javaScript) 자바스크립트 setInterval 사용해 주기적 JSON 특정 Key 의 Value 값 동적 업데이트 수행 본문

JavaScript

561. (javaScript) 자바스크립트 setInterval 사용해 주기적 JSON 특정 Key 의 Value 값 동적 업데이트 수행

투케이2K 2026. 6. 25. 20:09
728x90
반응형

[개발 환경 설정]

개발 툴 : Edit++ / Vscode

개발 언어 : JavaScript

 

[소스 코드]

-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------

- 개발 환경 : Web


- 개발 기술 : JavaScript / JSON / setInterval


- 사전) 👉 자바스크립트 setInterval() 간략 설명 : 

  >> setInterval() 은 JavaScript 에서 일정 시간마다 특정 함수를 반복 실행하는 타이머 함수입니다.

  >> 기본 문법 : const timerId = setInterval(callback, delay);

    - callback : 반복 실행할 함수
    - delay : 실행 주기(ms, 밀리초)
    - 반환값 : 타이머 ID

  >> setInterval() 사용 예제 코드 :
  
    setInterval(() => {

      console.log('실행');

    }, 1000); // 1초 마다 실행

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------

<!DOCTYPE HTML>
<html lang="ko" translate="no">
<head>
    <title>javaScriptTest</title>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- 반응형 구조 만들기 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

    <!-- Chrome / Edge (Chromium)에서 자동 번역 기능을 완전히 비활성화 -->
    <meta name="google" content="notranslate">

    <!-- 내부 CSS 스타일 지정 -->
    <style>

      html, body {
        width: 100%;
        height: 100%;
        margin : 0 auto;
        padding : 0;
        border : none;
        background-color: #666;
      }

    </style>





    <!-- [CDN 주소 설정] --> 
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>






    <!-- [자바스크립트 코드 지정] -->
    <script type="module">    


      // -----------------------------------------------------------------
      // ✅ [Window.onload 웹 브라우저 로드 완료]
      // -----------------------------------------------------------------
      window.onload = async function() {
        console.log("[window onload] : [html 최초 로드 및 이벤트 상시 대기 실시] : [start]");

        try {
          
          // ------------------------------------------------
          // 🟦 JSON 데이터 생성 수행
          // ------------------------------------------------  
          let jsonData = `
            {
              "state": {
                "desired": {
                  "command": "EVENT",
                  "action": 0
                }
              }
            }
          `;

          jsonData = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData; // Object 타입으로 변경

          console.log("jsonData : ", JSON.stringify(jsonData));

          

          // ------------------------------------------------
          // 🟦 방법 1. 경로를 알고 있는 경우
          // ------------------------------------------------ 
          // 3초마다 action 값을 0~10 사이 랜덤값으로 변경
          // ------------------------------------------------ 
          /*
          let runCnt = 1;

          let refreshTimer = setInterval(() => {
            console.log("refreshTimer : runCnt : ", runCnt);

            if (runCnt > 3){

              // 타이머 동작 종료
              console.error("refreshTimer : close : ", runCnt);

              if (refreshTimer) {
                clearInterval(refreshTimer);
                refreshTimer = null;              
              }

            }
            else {

              const randomValue = Math.floor(Math.random() * 10) + 1; // 1 ~ 10 범위

              jsonData.state.desired.action = randomValue;
              
              console.log("jsonData refresh : ", JSON.stringify(jsonData));

            }
            
            runCnt ++; // 카운트 증가
              
          }, 3000);
          // */



          // ------------------------------------------------
          // 🟦 방법 2. JSON 구조를 모르고 Key를 동적으로 찾아서 변경하는 경우
          // ------------------------------------------------ 
          // 3초마다 action 값을 0~10 사이 랜덤값으로 변경
          // ------------------------------------------------ 
          //*
          let updateValueByKey = function(obj, targetKey, newValue) {

            try {


              if (obj === null || obj === undefined || typeof obj !== 'object'){
                console.error('updateValueByKey : obj error');
                return false;
              }

              if (targetKey === null || targetKey === undefined || targetKey === ''){
                console.error('updateValueByKey : targetKey error');
                return false;
              }

              if (newValue === null || newValue === undefined){
                console.error('updateValueByKey : newValue error');
                return false;
              }

              for (const key in obj) {

                if (key === targetKey) {
                  obj[key] = newValue;
                  return true;
                }

                if (typeof obj[key] === 'object' && obj[key] !== null && obj[key] !== undefined) {
                  const found = updateValueByKey(obj[key], targetKey, newValue); // 재귀 호출
                  if (found) {
                      return true;
                  }
                }
              }

              return false;

            }
            catch(error){
              console.error('updateValueByKey : exception : ', error);
              return false;
            }
            
          }


          let runCnt = 1;


          let refreshTimer = setInterval(() => {
            console.log("refreshTimer : runCnt : ", runCnt);

            if (runCnt > 3){

              // 타이머 동작 종료
              console.error("refreshTimer : close : ", runCnt);

              if (refreshTimer) {
                clearInterval(refreshTimer);
                refreshTimer = null;              
              }

            }
            else {

              const randomValue = Math.floor(Math.random() * 10) + 1; // 1 ~ 10 범위

              let updateFlag = updateValueByKey(jsonData, 'action', randomValue);

              //let updateFlag = updateValueByKey(jsonData, 'command', "REFRESH");
              
              console.log("jsonData refresh : ",updateFlag, ' / ' , JSON.stringify(jsonData));

            }
            
            runCnt ++; // 카운트 증가
              
          }, 3000);
          // */

        }
        catch (exception) {
          console.error("[window onload] : [Exception] : ❌ 예외 상황 발생 : ", exception);

        }

      };


    </script>


</head>


<body>

</body>

</html>

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------

▶️ 64. (javascript/자바스크립트) JsonArray 에 담긴 JsonObject 객체 파싱해 특정 idx (순서) 로 정렬 실시

https://kkh0977.tistory.com/876

https://blog.naver.com/kkh0977/222399966146?trackingCode=blog_bloghome_searchlist


▶️ 187. (TWOK/UTIL) [Web/JavaScript] 자바스크립트 Deep Proxy (재귀 Proxy) JSON 객체 상태 변경 이벤트 감지 - 전체 데이터 변경 감지

https://kkh0977.tistory.com/8768

https://blog.naver.com/kkh0977/224252361170?trackingCode=blog_bloghome_searchlist


▶️ 62. (javascript/자바스크립트) jsonArray to jsonObject 형식 데이터 파싱 수행 실시

https://kkh0977.tistory.com/869

https://blog.naver.com/kkh0977/222398661411?trackingCode=blog_bloghome_searchlist


▶️ 510. (javaScript) [간단 소스] 자바스크립트 커스텀 json key 정렬 함수 생성 및 string , number , date 타입 asc , desc 정렬 수행

https://kkh0977.tistory.com/8695

https://blog.naver.com/kkh0977/224215514697?trackingCode=blog_bloghome_searchlist


▶️ 559. (javaScript) 자바스크립트 정규식 test() 사용해 올바르지 않은 JSON 특수 문자 따옴표 포함 여부 체크 및 replace 치환 수행

https://kkh0977.tistory.com/8935

https://blog.naver.com/kkh0977/224326054428?trackingCode=blog_bloghome_searchlist

-----------------------------------------------------------------------------------------
 
728x90
반응형
Comments