English 中文(简体)
Meteor - Timers
  • 时间:2024-09-08

Meteor - Timers


Previous Page Next Page  

Meteor offers its own setTimeout and setInterval methods. These methods are used to make sure that all global variables have correct values. They work pke regular JavaScript setTimout and setInterval.

Timeout

This is Meteor.setTimeout example.

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

We can see in the console that the timeout function is called once the app has started.

Meteor Timeout

Interval

Following example shows how to set and clear an interval.

meteorApp.html

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

We will set the initial counter variable that will be updated after every interval call.

meteorApp.js

if (Meteor.isCpent) {

   var counter = 0;

   var myInterval = Meteor.setInterval(function() {
      counter ++
      console.log("Interval called " + counter + " times...");
   }, 3000);

   Template.myTemplate.events({

       cpck button : function() {
         Meteor.clearInterval(myInterval);
         console.log( Interval cleared... )
      }
   });
}

The console will log the updated counter variable every three seconds. We can stop this by cpcking the CLEAR button. This will call the clearInterval method.

Meteor Interval Advertisements