Meteor有提供它自己的setTimeout和setInterval方法。這些方法被用於確保所有全局變數都具有正確的值。它們就像普通 JavaScript 中的setTimeout 和 setInterval 一樣工作。
Timeout - 超時
Meteor.setTimeout 的例子。
Meteor.setTimeout(function(){
console.log("Timeout called after three seconds..."); }, 3000);
當應用程式已經開始我們可以在超時函數調用(啟動 3 秒後調用),在控制臺中看到下麵的輸出結果。


Interval
接下來的例子顯示如何設置和清除interval。
meteorApp/client/app.html
<head>
<title>meteorApp</title>
</head>
<body>
<div>
{{> myTemplate}}
</div>
</body>
<template name = "myTemplate">
<button>CLEAR</button>
</template>
我們將設置將 counter 的初始變數在每次調用後更新。
meteorApp/client/app.js
if (Meteor.isClient) {
var counter = 0;
var myInterval = Meteor.setInterval(function(){
counter ++
console.log("Interval called " + counter + " times...");
}, 3000);
Template.myTemplate.events({
'click button': function(){
Meteor.clearInterval(myInterval);
console.log('Interval cleared...')
}
});
}
控制臺將每三秒鐘記錄更新計數器- counter 變數。我們可以通過點擊 CLEAR 按鈕清除。這將調用 clearInterval 方法。
上一篇:
Meteor Blaze
下一篇:
Meteor EJSON
