<aside> <img src="/icons/cursor-click_blue.svg" alt="/icons/cursor-click_blue.svg" width="40px" /> 빠른 이동을 원하시면, 아래 키워드를 클릭하세요!

</aside>

내장함수(타이머)

싸이월드 만들기 4탄

🌿 함수

함수란?

함수우리가 만드는 기능 입니다.

지금까지는 메서드 같은 자바스크립트에서 제공되는 기능 들을 사용했지만, 이제부터는 우리가 직접 기능을 만들어 사용해보도록 하겠습니다.

함수를 만들려면?

예를들어, 두 숫자를 더하는 함수(기능)을 만들어 봅시다.

  1. 아래의 그림에서 네모박스함수(기능) 입니다

  2. 상자로 들어가는 데이터 3, 5입력데이터(매개변수= parameter) 라고 합니다.

  3. 상자에서 반환되어 나오는 8결과데이터(반환데이터= return 값) 라고 합니다.


    🌿 함수의 종류

    함수의 선언식

    function 함수이름(param1, param2, ...){
        // ...code here
        return 결과값
    }
    

    함수의 표현식

    const 함수이름 = function**(param1, param2, ...){
        // ...code here
        return 결과값
    }
    

    변수에 할당된 함수는 함수 선언식과 어딘가 비슷하게 생기지 않았나요?

    비슷하게 보이지만, 어딘가 달라보이는 저 함수는 익명함수라고 부릅니다.

    나중에 호이스팅을 공부하시게 된다면 알게되실텐데, 함수선언식의 기명함수는 호이스팅의 영향을 받는 반면에 함수 표현식의 익명함수는 호이스팅의 영향을 받지 않습니다.

    ✅ 화살표 함수 : 실무함수

    const 함수이름 = ( param1, param2, ... )=>{
        // ...code here
        return 결과값
    }
    

    ❗️ 매개변수(parameter)와 return 값은 필수가 아닙니다. 매개변수와 리턴값은 있어도 되고 없어도 되는 값이기 때문에 반드시 적어주실 필요는 없습니다. 상황에 따라 필요하실 때 적절히 적어주시면 됩니다.

    함수 만들어보기 예제

    // 함수 선언식 - 더하기 함수 만들어보기**
    function add(a, b){
        return a+b
    }
    
    // 함수 표현식 - 빼기 함수 만들어보기**
    const minus = function (a, b){
        return a-b
    }
    
    // 화살표 함수 - 곱하기 함수 만들어보기
    const multiply = (a, b)=>{
        return a*b
    }
    

    만들어 둔 함수 실행시키기

    만들어 둔 함수를 실행시키려면, 해당 함수를 호출 해야 합니다.

    해당 함수를 호출 하는 방법은 함수의 이름을 불러주는 것 입니다.

    아래 예제를 통해 알아보도록 하겠습니다.

    //함수를 만들어 줍니다.
    function sayHi(){
        alert("안녕하세요 여러분!")
    }
    sayHi()
    

    함수가 매개변수를 받고있지 않은 경우에는 호출시 인자를 넘겨주지 않아도 되지만,

    아래와 같이 매개변수(파라미터)를 받고 있는 경우에는 호출시 적절한 인자(argu)를 넘겨주어야 합니다.

    // 함수를 만들어 줍니다.
    function calculator(a,b){
        return a+b
    }
    // 함수를 호출해줍니다.
    calculator(1,2)
    

    레벨업!

    ? 실무예제 - {함수} 언제 사용하나요? 실무에서 함수는 너무나도 많이 사용되기 때문에 언제 사용한다 단정할 수 없습니다.

    여러분들이 특정 기능이 필요하다 하실때마다 함수를 이용해서 만드시기때문에 기능이 필요하실때마다 사용하게 되실겁니다.

    // 로그인검증기능 만들기
    function validation(email, password){
      if(!email.includes("@")) {
      alert("이메일 주소를 다시 확인해주세요.")
      return false
    } else if(8<=password.length && password.length<=16){
      alert("8~16자의 영문, 숫자, 특수문자만 사용 가능합니다.")
      return false
    } else {
      return true
     }
    }
    
    // 로그인검증기능 사용하기
    const email = "email&naver.com"     // 사용자가 입력창에 입력한 이메일을 변수에 담기
    const password = "1234"             // 사용자가 입력창에 입력한 비밀번호를 변수에 담기
    validation(email, password)         // false
    
    

    🌿 내장함수(타이머)

    내장함수라는 것은 자바스크립트가 함수 선언을 미리 해놔서 호출만으로 사용할 수 있는 함수를 뜻합니다.

    내장함수의 종류

    내장 함수의 종류에는 여러가지가 있습니다. 하지만, 우리는 많이 사용하는 세가지 정도만 알아보도록 하겠습니다.

    alert

    메세지를 지정할 수 있는 경고 대화 상자를 띄웁니다.

    //alert 만들어보기 _ 콘솔에서 해보세요!
    alert("이렇게 만드시면 경고창이 생겨요!")
    

    setTimeout

    시간 지연함수로 입력 시간이 만료된 후 함수나 지정함 코드를 실행합니다.

    setTimeout(기능, 시간) // 기능은 함수이고, 시간은 밀리세컨드 단위입니다.
    

    setInterval

    시간 반복함수로 입력한 시간마다 함수를 반복적으로 호출하거나 코드를 실행합니다.

    setInterval(기능, 시간)         // 기능은 함수이고, 시간은 밀리세컨드 단위입니다.
    
    

    내장함수 예제

    setTimeout, setInterval

    // setTimeout 예제
    console.log("로딩을 시작합니다.")
    setTimeout(function(){
    		console.log("로딩 완료.")                        // 로딩을 시작합니다.
    }, 3000)                                           // 로딩 완료.
    
    // setInterval 예제
    setInterval(function(){
    		const now = new Date()
    		const minutes = now.getMinutes()
    		const seconds = now.getSeconds()
    
    		console.log(minutes + "분" + seconds + "초")         // 16분 11초
                                                            // 16분 12초
    }, 1000)                                                // 16분 13초
                                                            // 16분 14초
    																									      //	  ...
    
    

    실무적용 - { setInterval() 언제 사용하나요? } 휴대폰 인증시, 인증만료시간을 보여줄 때 사용합니다.

    위와 같은 인증 타이머를 만들기 위해 아래와 같은 로직으로 구성하시면 됩니다.

    let timer = 180
    setInterval(function(){
    		timer = timer - 1;
    		const minutes = Math.floor(timer / 60)
    		const seconds = timer - minutes * 60
    		console.log(minutes + ":" + seconds)
    }, 1000)
    

    시간지연함수와 시간반복함수의 종료

    시간지연함수와 시간반복함수는 중간에 강제로 종료할 수 있습니다.

    // 시간지연함수 강제종료
    const time = setTimeout(기능, 시간)    // 시간지연함수를 임시로 변수/상수에 저장해놓습니다.
    clearTimeout(time)              // 저장했던 시간지연함수를 종료합니다.
    
    // 시간반복함수 강제종료
    const time = setInterval(기능, 시간)   // 시간반복함수를 임시로 변수/상수에 저장해놓습니다.
    clearInterval(time)                   // 저장했던 **시간반복함수를 종료**합니다.
    

    각각의 종료 함수는 각자의 함수 안에서 사용할 수 있습니다. 즉, clearInterval은 setInterval안에서 사용할 수 있다는 뜻 입니다.


    🌿 템플릿 리터럴

    템플릿 리터럴이란?

    이전에 우리가 문자열과 변수를 이어줄 때 [ + ] 를 사용

    // 오늘 날짜 예쁘게 보여주기
    console.log("오늘은 " + year + "년 " + month + "월 " + date + "일 입니다.")
                              // 오늘은 2021년 4월 3일 입니다.
    
    // 지금 시간 예쁘게 보여주기
    console.log("지금은 " + hours + "시 " + minutes + "분 " + seconds + "초 입니다." )
                              // 지금은 13시 30분 17초 입니다.
    

    하나만 더! 문장과 변수를 함께 쓸 때, 더하기(+)로 연결하는 것 보다 더 깔끔한 방법이 있나요? 있습니다! 아래와 같이 해보세요!

    console.log(`오늘은 ${year}년 ${month}월 ${date}일 입니다.`)
    console.log(`오늘은 ${hours}시 ${minutes}분 ${seconds}초 입니다.`)
    

    이렇게 사용하는 방식을 템플릿 리터럴(Template literal) 이라고 합니다. 실무에서는 이 방식을 사용합니다.


    🌿 싸이월드 만들기 4탄

    cyworld figma

    ⭐️ Reference 아래는 레퍼런스 코드입니다. 과제를 완료하기 전 미리 확인하지 마세요!

    jukebox-html

    <!DOCTYPE html>
    <html lang="ko">
    <head>
        <title>Jukebox</title>
        <link href="./styles/jukebox.css" rel="stylesheet">
        <link rel="stylesheet" href="<https://pro.fontawesome.com/releases/v5.10.0/css/all.css>" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
    </head>
    </head>
    <body>
        <div class="wrapper">
            <div class="wrapper__header">
                <div class="header__title">
                    <div class="title">추억의 BGM</div>
                    <div class="subtitle">TODAY CHOICE</div>
                </div>
                <div class="devideLine"></div>
                <div class="albumWrapper">
                    <div class="albumWrapper__item">
                        <img class="album-thumbnail" src="./images/jukebox-01.png">
                        <div class="album-songtitle">Y(Please Tell Me Why)</div>
                        <div class="album-artist">프리스타일</div>
                    </div>
                    <div class="albumWrapper__item">
                        <img class="album-thumbnail" src="./images/jukebox-02.png">
                        <div class="album-songtitle">눈의 꽃</div>
                        <div class="album-artist">박효신</div>
                    </div>
                    <div class="albumWrapper__item">
                        <img class="album-thumbnail" src="./images/jukebox-03.png">
                        <div class="album-songtitle">사랑했나봐</div>
                        <div class="album-artist">윤도현</div>
                    </div>
                </div>
            </div>
            <div class="wrapper__body">
                <div class="header__title">
                    <div class="title">추억의 BGM</div>
                    <div class="subtitle">TODAY CHOICE</div>
                </div>
                <table class="albumTable">
                    <tr>
                        <th class="albumTable__checkbox"><input type="checkbox"></th>
                        <th class="albumTable__number">번호</th>
                        <th class="albumTable__song">곡명</th>
                        <th class="albumTable__artist">아티스트</th>
                    </tr>
                    <tr>
                        <td class="album-table-checkbox"><input type="checkbox" /></td>
                        <td class="album-table-number">1</td>
                        <td class="album-table-song"><i class="fas fa-caret-right arrow"></i> 눈의 꽃</td>
                        <td class="album-table-artist">박효신</td>
                    </tr>
                    <tr>
                        <td class="album-table-checkbox"><input type="checkbox" /></td>
                        <td class="album-table-number">2</td>
                        <td class="album-table-song"><i class="fas fa-caret-right arrow"></i> 사랑스러워</td>
                        <td class="album-table-artist">김종국</td>
                    </tr>
                    <tr>
                        <td class="album-table-checkbox"><input type="checkbox" /></td>
                        <td class="album-table-number">3</td>
                        <td class="album-table-song"><i class="fas fa-caret-right arrow"></i> 내사람: Partner For Life</td>
                        <td class="album-table-artist">SG워너비</td>
                    </tr>
                    <tr>
                        <td class="album-table-checkbox"><input type="checkbox" /></td>
                        <td class="album-table-number">4</td>
                        <td class="album-table-song"><i class="fas fa-caret-right arrow"></i> Love Love Love</td>
                        <td class="album-table-artist">에픽하이</td>
                    </tr>
                    <tr>
                        <td class="album-table-checkbox"><input type="checkbox" /></td>
                        <td class="album-table-number">5</td>
                        <td class="album-table-song"><i class="fas fa-caret-right arrow"></i> 애인...있어요</td>
                        <td class="album-table-artist">이은미</td>
                    </tr>
                </table>
                <div class="albumTable__footer">
                    <div class="albumTable__footer__left">
                        <button>듣기</button>
                    </div>
                    <div class="albumTable__footer__center">
                        | <span>1</span> |
                    </div>
                    <div class="albumTable__footer__right">
                        <button>이동</button>
                        <button>배경음악 등록</button>
                    </div>
                </div>
            </div>
        </div>
    </body>
    </html>
    
    

    jukebox-css

    * {
        box-sizing: border-box;
        margin: 0px;
        padding: 0px;
    }
    
    html, body {
        width: 100%;
        height: 100%;
    }
    
    .wrapper {
        width: 100%;
        height: 100%;
        padding: 20px 30px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;
    }
    
    .wrapper__header {
        width: 100%;
    }
    
    .header__title {
        display: flex;
        flex-direction: row;
        align-items: center;
    }
    
    .title {
        color: #55b2d4;
        font-size: 13px;
        font-weight: 700;
    }
    
    .subtitle {
        padding-left: 5px;
        font-size: 8px;
    }
    
    .devideLine {
        width: 100%;
        border-top: 1px solid gray;
    }
    
    .albumWrapper {
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        padding-top: 12px;
    }
    
    .albumWrapper__item .album-thumbnail {
        width: 120px;
        height: 120px;
    }
    
    .albumWrapper__item .album-songtitle {
        font-size: 11px;
        font-weight: bold;
        color: #0f465e;
        display: flex;
        flex-direction: row;
        justify-content: center;
    }
    
    .albumWrapper__item .album-artist {
        font-size: 10px;
        font-weight: bold;
        color: gray;
        display: flex;
        flex-direction: row;
        justify-content: center;
    }
    
    .wrapper__body {
        width: 100%;
    }
    
    .albumTable {
        border-spacing: 0px;
        width: 100%;
        padding-top: 8px;
    }
    
    .albumTable th {
        height: 20px;
        font-size: 10px;
        font-weight: bold;
        color: gray;
        background-color: #EEEEEE;
        padding-top: 5px;
        border-top: 1px solid gray;
        border-bottom: 1px dashed gray;
    }
    
    .albumTable td {
        height: 20px;
        font-size: 10px;
        color: #0F465E;
        border-bottom: 1px dashed gray;
    }
    
    .album-table-checkbox {
        width: 5%;
        text-align: center;
    }
    
    .album-table-number {
        width: 10%;
        text-align: center;
    }
    
    .album-table-song {
        width: 45%;
        text-align: left;
    }
    
    .album-table-artist {
        width: 30%;
        text-align: left;
    }
    
    .arrow {
        width: 10px;
        height: 10px;
        text-align: center;
        color: red;
        border: 1px solid gray;
        border-radius: 2px;
    }
    
    .albumTable__footer {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        font-size: 10px;
        padding-top: 10px;
    }
    .albumTable__footer button {
        font-size: 8px;
        color: gray;
        padding: 3px;
        background: linear-gradient(180deg, #FFFFFF 0%, #FFFFFF 57.43%, #DDDDDD 100%);
        border: 1px solid gray;
        border-radius: 5px;
    }
    .albumTable__footer__center span {
        color: red;
    }