[JS] setTimeout(),setInterval()

영태·2022년 3월 20일
0

[JS] Algorithm Study

목록 보기
8/8

1. setTimout(function(),delay,arg1,arg2...)

delay(단위 ms)이후 function()을 실행한다

  • 자동 로그아웃 알림
setTimeout(
function(){console.log("자동 로그아웃")}
,2000) 
  • 결과값
//2초 후
"자동 로그아웃"

아래와 같이 값으로 arg1,arg2...등 인수를 설정하여 function()에 인수값을 넘겨줄 수도 있다

function sayHi(who, phrase) {
  alert( who + ' 님, ' + phrase );}
setTimeout(sayHi, 1000, "홍길동", "안녕하세요."); // 홍길동 님, 안녕하세요.

2. setInterval(function(),delay,arg1,arg2...)

  • delay(단위 ms)마다 function()을 실행한다
  • 마찬가지로 arg1,arg2...등 argument를 설정해 넘겨줄 수 있다
  • setInterval()을 이용해 초시계 만들기
let timer
function getTime(watch){
    time= watch*60
    timer=setInterval(
        ()=>{
            if(time>0){
                const minute =Math.floor(time/60)
                const second = String(time%60).padStart(2,"0")
                time-=1
                console.log( minute+":"+second+ " 남았습니다" )
            }else{
                clearInterval(timer)
                console.log("종료")}}
                ,1000)}
getTime(1) 
  • 결과값
1:00 남았습니다
0:59 남았습니다
0:58 남았습니다
...
  • setTimeoutsetInterval은 우리가 실행을 취소하기 위해 사용할 수 있는 "timer identifier"를 반환한다
  • 이 반환 값을 clearTimeout()clearInterval에 인수값으로 넣어 종료시킬 수 있다
  • 따라서 delay기간 안에 함수를 종료시키고 싶다면 변수값에 다음과 같이 넣어 종료시킬수 있다
timeid=setTimeout(
	function(){
    if(timeid>1000){console.log("자동 로그아웃")}
    else if(timeid=1000){clearTimeout(timeid)}}
  	,2000) 
  • 결과값
없음
profile
개발 공부중

0개의 댓글