다른 함수의 이름과 1/1000초 단위의 시간값을 파라미터로 설정하여
정해진 시간에 한번씩 파라미터로 전달된 함수를 반복적으로 호출한다.
// 함수를 1초에 한번씩 반복해서 자동 호출한다.
setInterval(함수, 1000);
// 익명함수 : 함수의 이름이없다.
// 파라미터 형태로 전달되는 함수를 콜백함수라고 한다.
setInterval(function(){
.. 1초마다 반복 실행될 구문 ..
}, 1000);
<body onload="startTime()">
<h1 id="timer"></h1>
<script>
function printTime(){
// 현재시간을 구한다.
let days = ['일', '월', '화', '수', '목', '금', '토'];
let mydate = new Date();
let yy = mydate.getFullYear();
let mm = mydate.getMonth() + 1;
let dd = mydate.getDate();
let i = mydate.getDay();
let day = days[i];
let hh = mydate.getHours();
let mi = mydate.getMinutes();
let ss = mydate.getSeconds();
// 완성된 현재 시각
let result = yy + "-" + mm + "-" + dd + " "
+ day + "요일" + hh + ":" + mi + ":" + ss;
// id 속성값이 timer인 요소에게 결과를 출력한다.
document.getElementById("timer").innerHTML = result;
}
function startTime(){
// printTime함수를 1초에 한번씩 반복해서 자동 호출한다.
setInterval( printTime, 1000 );
}
</script>
</body>
<script>
// 올해는 앞으로 00일 남았습니다.
function getDday(y, m, d){
let today = new Date();
let dday = new Date(y, m-1, d);
let cnt = dday.getTime() - today.getTime();
let n = Math.ceil(cnt / (24*60*60*1000));
return n;
//return Math.ceil((cnt / 24*60*60*1000));
}
let date = new Date();
let y = date.getFullYear();
let dday = getDday(y, 12, 31);
document.write( "<h1>올해는 앞으로 " + dday + "일 남았습니다.</h1>" );
</script>
객체에 정의된 function -> 메서드라고 한다.
객체이름.함수이름 = function(파라미터){
};
객체 안에 포함된 메서드에서 다른 메서드를 호출하거나, 활용하고자
하는 경우에는 this 키워드를 사용한다.
this.변수이름;
this.함수이름();
<script>
// 객체 생성
let people = {};
// 변수추가
people.name = "자바학생";
people.gender = "여자";
people.sayName = function(){
document.write("<h1>" + this.name + "</h1>");
};
people.sayGender = function(){
document.write("<h1>" + this.gender + "</h1>");
};
people.saySomething = function(msg){
document.write("<h1>" + msg + "</h1>");
};
people.getName = function(){
return this.name;
};
people.getGender = function(){
return this.gender;
};
document.write("<h1>" + people.name + "님은 "
+ people.gender + "입니다. </h1>");
document.write("<h1>---------------------</h1>");
people.sayName();
document.write("<h1>---------------------</h1>");
document.write("<h1>" + people.getName() + "님은 "
+ people.getGender() + "입니다. </h1>");
people.saySomething("JavaScript!!");
</script>
<script>
// 일반적인 함수 선언
function myFunction(){
document.write("<h1>Hello Javascript</h1>");
}
// javascript는 함수와 변수가 동급이다.
// 함수의 이름을 변수에 대입할 수 있다.
let value = myFunction;
// 함수가 대입된 변수는 그 자신이 함수처럼 동작한다.
value();
document.write("<h1>--------------------------------</h1>");
// 함수를 변수에 대입할 수 있기 때문에,
// 처음부터 변수에 함수의 내용을 대입하는 것이 가능하다.
let value2 = function(){
document.write("<h1>Hello Javascript2</h1>");
};
value2();
</script>