본문 바로가기

21 - 2학기/슬기로운 코딩생활

[TIL] 노마드코더 JS 5.0 ~ 6.2

TAB 2021 겨울방학 학회활동 [슬기로운 코딩생활]

2주차 TIL입니다.

작성자 : 38기_조주희


// #5 clock

setInterval(함수, 시간)

: 일정 시간 간격을 두고 함수를 실행하는 방법(밀리세컨드가 단위)

setTimeout(함수, 시간)

: 일정 시간 간격을 두고 함수를 실행하는 방법

function sayHello () {
    console.log("hello");
}

setInterval(sayHello, 5000) // 5초에 한번씩 콘솔에 hello 출력

setTimeout(sayHello, 5000) // 5초 이후에 콘솔에 hello 출력 (그 이후엔 출력 되지 않음)

Date 객체

new Date() 를 호출하면 새로운 Date 객체가 만들어짐.

let now = new Date();
console.log(now); // 현재 날짜 및 시간이 보여짐

new Date(year, month, date, hours, minutes, seconds, ms)

   주어진 인수를 조합해 만들 수 있는 날짜가 저장된 객체가 반환됨

 

기본 함수

함수명 의미 설명
getFullYear() setFullYear() 년도  
getMonth() setMonth() 0~11 > 1월~12월
getDate() setDate()  
getDay() setDay() 요일 0~6 > 일요일 ~ 토요일
getHours() setHours() 시간  
 getHours() setHours()  
getMilliseconds() setMilliseconds() 밀리초  
getSeconds() setSeconds()  
getTime() setTime() Unix 타임 1970/1/1 12:00 기준 경과한 밀리 초

padStart(newLength, "padString")

: 현재 문자열의 시작을 다른 문자열로 채워 주어진 길이 값을 갖는 문자열을 반환함

무조건 String 형태를 받아야 함

var str = "Hi";

console.log(str.padStart(10));      // "        Hi"
console.log(str.padStart(10, "!")); // "!!!!!!!!Hi"

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Momentum App</title>
    <link rel = "stylesheet" href = "style.css">
    <style>
        .hidden { 
            display: none;
        }
    </style>
</head>
<body>
    <form class = "hidden" id = "login-form">
        <input required maxlength = "15" type = "text" placeholder = "What is your name?"/>
        <button>Log In</button>
    </form>
    <h1 id = "greeting" class = "hidden"></h1>
    <h2 id="clock">00:00:00</h2>
    <script src = "js/clock.js"></script>
    <script src = "js/greeting.js"></script>
</body>
</html>

clock.js

const clock = document.querySelector("h2#clock");

function getClock () {
    const date = new Date();
    const hour = String(date.getHours()).padStart(2,"0");
    const minutes = String(date.getMinutes()).padStart(2,"0");
    const second = String(date.getSeconds()).padStart(2,"0");
    clock.innerText = `${hour}:${minutes}:${second}`;
}
getClock();
setInterval(getClock, 1000)

// #6 Quotes and Background

Math 객체

대표적인 메소드

함수명 설명
min() 인수로 전달받은 값 중 가장 작은 수 반환
max() 인수로 전달받은 값 중 가장 큰 수 반환
random() 무작위 숫자 반환 ( random()*10 = 0~9 )
round() 인수로 전달받은 값을 소수점 첫 번쨰 자리에서 반올림하여 반환
floor() 인수로 전달받은 값과 같거나 작은 수 중에서 가장 큰 정수 반환( floor(11.01) = 11 )
ceil() 인수로 전달받은 값과 같거나 큰 수 중에서 가장 작은 정수 반환( ceil(11.01) = 12 )
sin() 인수로 전달받은 값의 사인(sin)함수 값을 반환
PI 원주율 제공

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Momentum App</title>
    <link rel = "stylesheet" href = "style.css">
    <style>
        .hidden { 
            display: none;
        }
        img {
            height: 800px;
        }
    </style>
</head>
<body>
    <form class = "hidden" id = "login-form">
        <input required maxlength = "15" type = "text" placeholder = "What is your name?"/>
        <button>Log In</button>
    </form>
    <h1 id = "greeting" class = "hidden"></h1>
    <h2 id="clock">00:00:00</h2>
    <div id="quote">
        <span></span>
        <span></span>
    </div>
    
    <script src = "js/clock.js"></script>
    <script src = "js/greeting.js"></script>
    <script src = "js/quotes.js"></script>
    <script src = "js/background.js"></script>
</body>
</html>

quotes.js

const quotes = [
    {
      quote: "The way to get started is to quit talking and begin doing.",
      author: "Walt Disney",
    },
    {
      quote: "Life is what happens when you're busy making other plans.",
      author: "John Lennon",
    },
    {
      quote:
        "The world is a book and those who do not travel read only one page.",
      author: "Saint Augustine",
    },
    {
      quote: "Life is either a daring adventure or nothing at all.",
      author: "Helen Keller",
    },
    {
      quote: "To Travel is to Live",
      author: "Hans Christian Andersen",
    },
    {
      quote: "Only a life lived for others is a life worthwhile.",
      author: "Albert Einstein",
    },
    {
      quote: "You only live once, but if you do it right, once is enough.",
      author: "Mae West",
    },
    {
      quote: "Never go on trips with anyone you do ntot love.",
      author: "Hemmingway",
    },
    {
      quote: "We wander for distraction, but we travel for fulfilment.",
      author: "Hilaire Belloc",
    },
    {
      quote: "Travel expands the mind and fills the gap.",
      author: "Sheda Savage",
    },
];

const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");

const todaysQuote = quotes[Math.floor(Math.random()*quotes.length)];

quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;

background.js

const images = [
    "0red.jpg", 
    "1orange.jpg", 
    "2yellow.jpg", 
    "3green.jpg", 
    "4blue.jpg", 
    "5navy.jpg", 
    "6purple.jpg"
];

const chosenImage = images[Math.floor(Math.random() * images.length)];

const bgImage = document.createElement("img"); // 새로운 요소 생성

bgImage.src = `img/${chosenImage}`;

document.body.appendChild(bgImage);