Javascript Day4

Jisu Lee·2023년 2월 27일
0


오늘은 노마드코더 강의 수강 4일차입니다.

#5.0 (Intervals)

create a new file called clock.js and put that into the folder called 'js', then import them into html

<script src="js/greetings.js"></script>
<script src="js/clock.js"></script> 

interval is something that you want to happen every certain time

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

//you need a function and the time that you want things to happen, the time should be inputted in milliseconds so 5000 milliseconds = 5 seconds
setInterval(sayHello, 5000);

#5.1 (Timeouts and Dates)

interval : repeat after a certain amount of time
(ex. console.log every 5 seconds)
timeout : certain event once at a certain amount of time
(ex. console.log once after 5 seconds)

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

setTimeout(sayHello, 5000);

javascript code to make a clock

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

function getClock (){
    const date = new Date();
    clock.innerText =(`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`)
}

//we immediately call the function when we first open the window
getClock ()
//and it keeps going
setInterval(getClock, 1000);

the output

#5.2 (PadStart)

however the second is displayed as 1,2,3 not 01, 02, 03 because they are just getting seconds from 0 to 59, so we need to format the seconds to look like 01,02,03

//if we have a string that is 1 string long which is "1", then we make it two characters long, and we add 0 infront of them (because it is padStart, we also have padEnd, that puts the certain character in the end), then the output of the following code will be "01"
"1".padStart(2,"0")

another example of padStart would be

the final javascript code using padStart

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

function getClock (){
    const date = new Date();
  //we get numbers so we want them to be converted to strings
    const hours = String(date.getHours()).padStart(2,"0");
    const minutes = String(date.getMinutes()).padStart(2,"0");
    const seconds = String(date.getSeconds()).padStart(2,"0");
    clock.innerText =(`${hours}:${minutes}:${seconds}`)
}

//we immediately call the function when we first open the window
getClock ()
//and it keeps going, we want to call the function every second over and over again so we are using the interval
setInterval(getClock, 1000);

the output

0개의 댓글