2014-12-14 3 views
2

시계 + 날짜, 현재 날씨, 7 일 일기 예보, 뉴스 및 캘린더 이벤트 사이를 반복하는 간단한 페이지를 만들려고합니다. 이 '항목'은 기능을 사용할 때 호출됩니다.30 초마다 다른 함수를 호출하는 JavaScript 루프

예 : 나는 다음과 같은 함수를 만들었습니다 :

displayTime();  // Time + date using Moment.js 
currentWeather(); // Current weather using Forecast.io  (AJAX call) 
forecastWeather(); // Weekly forecast of the weather   (AJAX call) 
latestNews();  // Latest headlines from RSS source/s  (AJAX call) 
calendarEvents(); // Calendar events from iCloud calendars 

그들은 모두 스스로 호출 할 때 완벽하게 작동합니다. jQuery 문서를 준비 할 때 clock + date 함수를 호출하고 30 초를 기다린 후 다음 함수 (현재 날씨)를 호출하려고합니다. 모든 함수가 루프를 통과 한 후에는 루프가 시계로 돌아가서 다시 시작하기를 바랍니다.

어떻게 할 수 있습니까?

다시 편집 : Chop의 제안을받은 후 시계가 매초마다 계획대로 업데이트되지만 30 초마다 기능이 전환되지 않습니다.

jQuery(document).ready(function ($) {  
    function displayOne(){ 
     displayTime(); 
     setTimeout(displayTwo, 30000); 
    } 
    function displayTwo() { 
     currentWeather(); 
     setTimeout(displayOne, 30000); 
    } 
    displayOne(); 
    setInterval(displayTime, 1000); 
}); 
+0

것 사용 'setInterval'과'setInterval'을's를 사용하고 싶은 곳에서 사용하려면 etTimeout'. 또한 이와 같은 기능을 랩 할 필요가 없습니다. 그냥'setInterval (updateTime, 1000)'을 사용하십시오. – Witiko

+0

아마도 더 중요한 것은 - 동시에 'displayOne' 함수를 정의하고 실행하지 마십시오. 이런 식으로하면'displayOne'이라는 이름은'displayEne' 함수 내부에서만 볼 수 있고 외부에서는 볼 수 없습니다 ('ReferenceError : displayOne is not defined'). 'displayOne'을 정의한 다음 호출하십시오. 'displayTwo'도 마찬가지입니다. – Witiko

+0

Witiko, 전화를 걸기 전에 특정 기능을 정의하는 방법은 무엇입니까? 예를 들어 주시겠습니까 ..? –

답변

5

당신은처럼 그들을 체인 수있는이

function callFx(fx) { 
    setTimeout(fx, 30000) 
} 

function function1() { // update weather 
    callFx(function2) 
} 
function function2() { // update time 
    callFx(function3) 
} 
function function3() { // some operation 
    callFx(function1) 
} 

또는 setInterval을

var functions = [function1, function2, function3] 
var index = 0 

setInterval(function() { 
    functions[index]() 
    if(!functions[++index]) index = 0 
}, 30000) 

는 전체 코드 당신은`당신이 원하는 setTimeout`를 사용

jQuery(document).ready(function ($) {  
    function displayOne(){ 
     setTimeout(displayTwo, 30000) 
    } 
    function displayTwo() { 
     currentWeather() 
     setTimeout(displayOne, 30000) 
    } 
    displayOne() 
    setInterval(updateTime, 1000) 
}) 
+1

또는 모듈러 산술을 원한다면'index = (index + 1) % functions.length'. – Witiko

+0

setInterval은 좋은 아이디어입니다. 하지만 내가 직면하고 있다고 생각하는 문제는'displayTime();'setTimeout을 사용하여 매초마다 시간을 업데이트합니다. setInterval과 setTimeout을 모두 같이 사용할 수 있습니까? 간단히 말해서'displayTime();'함수를 다음과 같이 사용할 수 있습니까 :'setTimeout (function {) {displayTime();}, 1000);' –

+1

예, setTimeout과 setInterval 각 타이머는 별도의 ID로 작동하기 때문에 문제없이 사용할 수 있습니다. 타이머에 대한 자세한 정보는 http://javascript.info/tutorial/settimeout-setinterval – Chop

1

당신이 바로 그 위젯의 현재 상태에 따라 당신의 함수 중 하나를 호출하여 위젯의 내용을 변경을 담당하는 다른 함수를 호출하는 트리거 setInterval()를 사용할 수 있습니다.

관련 문제