Meteor - 計時器



Meteor 提供自己的 setTimeoutsetInterval 方法。這些方法用於確保所有全域性變數都具有正確的值。它們的工作方式與常規 JavaScript setTimoutsetInterval 類似。

超時

這是 Meteor.setTimeout 示例。

Meteor.setTimeout(function() {
   console.log("Timeout called after three seconds...");
}, 3000);

我們可以在控制檯中看到,超時函式在應用程式啟動後被呼叫。

Meteor Timeout

間隔

以下示例展示如何設定和清除間隔。

meteorApp.html

<head>
   <title>meteorApp</title>
</head>
 
<body>
   <div>
      {{> myTemplate}}
   </div>
</body>
 
<template name = "myTemplate">
   <button>CLEAR</button>
</template>

我們將設定將在每次間隔呼叫後更新的初始 counter 變數。

meteorApp.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 變數。我們可以透過單擊 清除 按鈕來停止此操作。這將呼叫 clearInterval 方法。

Meteor Interval
廣告
© . All rights reserved.