2017-01-05 13 views
0

첫 번째 함수를 반복적으로 실행하려고합니다. 두 번째 기능에서와 마찬가지입니다. 어디에서 봐야하나요?이 함수를 간격으로 수행하는 방법

 (function printLetterByLetter() { 
    var i = 0; 
    var destination = "comment"; 
    var RandomComment = [ 
    "Did you choose that outfit?" 
    , "I like trains."]; 
    var message = RandomComment[Math.floor(Math.random() * RandomComment.length)]; 
    var typewriter = function() { 
     document.getElementById(destination).innerHTML += message.charAt(i); 
     i++; 
     if (i > message.length) { 
      clearInterval(typespeed); 
     } 
    } 
    var speed = 60; 
    var typespeed = setInterval(typewriter, speed) 
}()); 



(function printLetterByLetter() { 
    var destination = "comment"; 
    var frequency = 1000; 
    var RandomComment = [ 
     "Did you choose that outfit?" 
     , "I like trains."]; 
    var RandomCommentTimer = setInterval(function() { 
     var message = RandomComment[Math.floor(Math.random() * RandomComment.length)]; 

    }, frequency) 
}()); 

그래서 난 할 노력하고있어 하나 기능/모듈을하는 것입니다 세트 속도 (첫 번째 함수)에서 임의의 주석으로 유형. 설정된 시간이 지나면 주석이 사라지고 새 주석이 입력됩니다 (두 번째 기능). 그리고 두 번째 기능처럼 이것은 계속 될 것입니다. 지금까지 나는 그것이 내가 생각하기에 자신이 작동하도록 만들지 않았습니다. 누군가가 stackoverflow에서 나를 도울 수 있는지 보겠습니다.

누구든지 어디에서 찍을 지 조언을 줄 수 있다면, 그 또한 가장 환영받을 것입니다.

+0

확실하지 무슨 질문인가? – guest271314

+0

(당신이 호출에 그들에게 어떤 값을 할당하지 않는 한) 당신은 인생의 몸 안에 같은 이름의 바르를 선언 두 번째 인생이 정의되지 않습니다 그 인수 (대상 등)에서 이례적인 일이다. 둘째, 둘 다'# comment'에 출력합니다 - 그래서 어떻게 둘 다 (별개의 "함수"또는 하나의 함수로) 실행할 수 있다고 생각합니까? –

+0

두 함수는 본질적으로 동일하지만 유일한 차이점은'RandomComment' 배열의 메시지입니다. 어떻게 그들을 결합하고 싶습니까? 게시물이 짧은 것, 그래서 – Barmar

답변

0

함수 외부에서 함수 매개 변수를 설정하고 변경 한 다음 내부에서 액세스 할 수 있습니다. 주의 할 점은 설정시 앞에 var을 넣을 수 없다는 것입니다. var를 앞에 두지 않으면 현재 범위 밖에서 액세스 할 수 있습니다.

destination = "comment"; 
frequency = 6000; 
(function printLetterByLetter() { 
//now you have access to destination and frequency as they are defined before the function is called 
var RandomComment = [ 
"Did you choose that outfit?" 
, "I like trains."]; 
var RandomCommentTimer = setInterval(function() { 
    var message = RandomComment[Math.floor(Math.random() * RandomComment.length)]; 
    document.getElementById(destination).innerHTML = message; 
}, frequency) 
}()); 
+0

네, 고맙습니다. 그러나 이것이 내가 붙어있는 부분이 아닙니다. –