2013-04-17 30 views
1

我想創建一個計時器,我在我的JavaScript文件中的字符串是:流星的setInterval - 更新每個第二

function timer(){ 
    var date = new Date(); 
    Template.pomodoro.timer = function() { return date}; 
    Template.pomodoro.message = function() { return "test message"}; 

} 


if (Meteor.isClient) { 
     Meteor.setInterval(timer(), 1000); 
} 

if (Meteor.isServer) { 
    Meteor.startup(function() { 
    // code to run on server at startup 

    }); 
} 

我要推到所有的瀏覽器相同的定時器(計算服務器端),以讓他們同步。

模板只是第一次更新,爲什麼每秒不更新?

感謝 弗朗西斯

回答

2

嘗試:

if (Meteor.isClient) { 
     Meteor.setInterval(function(){timer()}, 1000); 
} 

或者:

if (Meteor.isClient) { 
     Meteor.setInterval(timer, 1000); 
} 

這是因爲的setInterval的第一個參數必須是函數指針,你正在使用()這意味着你是執行者g函數而不是傳遞它。

4

這是什麼爲我工作的客戶端。我發現把服務器時間推到客戶端上最簡單的做法是將當前時間投入收集並簡單地在客戶端上使用該值。

if (Meteor.isClient) { 
    Template.pomodoro.timer= function() { 
     return Session.get("dateval"); 
    }; 
    Template.pomodoro.message= function() { 
     return "My Message"; 
    }; 

    Meteor.setInterval(function() { 
     Session.set("dateval",Date()); 
     console.log(Session.get("dateval")); 
    }, 1000); 
}