Meteor - Timers



Meteor offers its own setTimeout and setInterval methods. These methods are used to make sure that all global variables have correct values. They work like 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>
   <div>
      {{> myTemplate}}
   </div>
</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.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...')
      }
   });
}

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

Meteor Interval
Advertisements