JaveScript

[노마드코더] Vanilla_Js (5강,6강 - Clock, Quotes and Background)

SanL 2023. 5. 15. 00:18

JavaScript


Clock : setInterval, setTimeout

‣setInterval : setInterval 고정된 시간(ms) 지연으로 함수를 반복적으로 호출하거나 코드 스니펫을 실행한다.

: setInterval은 두개의 인자를 받는다.
첫번째 인자는 내가 실행하고자 하는 함수를 받는다.
두번째는 내가 호출하는 함수를 몇 ms 간격으로 설정할건지 넣어주면 된다.

‣setTimeout : 일정 시간(ms)이 지난 후 함수 실행한다.

: setTimeout은 setInterval과 비슷한 문법을 가지고있지만,
setTimeout은 내가 실행시키고 싶은 함수를 얼마나 뒤에 실행시키고 싶은지를 출력한다.
문법은 setInterval과 동일

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

sayHello(); // 바로 함수를 실행시킴

setInterval(sayHello, 5000) // sayHello 함수를 5초의 간격으로 출력

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

Date

‣new Date()

:생성자로 호출할 경우 새로운 Date객체를 반환한다.

let toDay = new Date();
console.log(toDay); // 오늘의 날짜와 시간이 반환됨.

‣인스턴스 메서드 : Data,prototype.(ect...)

: Date.prototype.(getDate(),getDay(),getfullYear()) 등..
Date를 이용해서 여러가지 형식을 이용할 수 있으니 [mdn 참고] 하자
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date

‣padStart(maxLength,fillString)

: padStart(최소 글자, "그렇지 않을 때 넣을 문자")
쉽게 말해서, padStart는 문자열의 최소길이를 알려주고, 이 최소길이보다 작을 때, 특정문자열을 채워주는 것

  let name = "San";
  console.log(name.padStart(5, "^"); 
  // 최소 길이를 알려주고 name의 문자열 길이가 5보다 작으면 ^작은 길이만큼 출력

[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(); // Date() 라는 생성자 함수 생성 ->Date 객체 속성과 여러 메소드에 접근하기 위해 선언
    const hour = String(date.getHours()).padStart(2,"0"); // padStart()는 문자열에만 적용되기 때문에 묶어줌
    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)

Quotes and Background

‣Math.

: 이전에 블로그 포스팅 해놓은 부분 확인해주시면 감사합니다.

[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(first_child)
        <span></span> // (last_child)
    </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)]; // floor은 소수점 내림 / random 소수점 0~9사이 숫자를 ㅂ반환해줌

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

[Background.js]

const images = [
    "0.jpg",
    "1.jpg",
    "2.jpg",
    "3.jpg",
    "4.jpg",
    "5.jpg",
];

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

const image = document.createElement("img");

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

document.body.appendChild(image);