Meteor提供了自己的setTimeout和setInterval方法,这些方法用于确保所有全局变量都具有正确的值,它们的工作方式类似于常规JavaScript setTimeout和setInterval。
Timeout函数
这是Meteor.setTimeout示例。
Meteor.setTimeout(function() { console.log("Timeout called after three seconds..."); }, 3000);
无涯教程可以在控制台中看到,一旦应用启动,就会调用超时功能。
![Meteor 暂停](http://dev-img.mos.moduyun.com/20231017/35e03d50-a0a0-41bb-847f-b8798900219e.jpg)
Interval函数
以下示例显示如何设置和清除间隔。
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...') } }); }
控制台将每三秒钟记录一次更新的计数器变量,无涯教程可以通过单击CLEAR按钮来停止此操作,这将调用clearInterval方法。
![Meteor 间隔](http://dev-img.mos.moduyun.com/20231017/bd29e262-a835-45eb-81b5-3420e5a0b00a.jpg)