Meteor提供了自己的setTimeout和setInterval方法,这些方法用于确保所有全局变量都具有正确的值,它们的工作方式类似于常规JavaScript setTimeout和setInterval。
这是Meteor.setTimeout示例。
Meteor.setTimeout(function() { console.log("Timeout called after three seconds..."); }, 3000);
无涯教程可以在控制台中看到,一旦应用启动,就会调用超时功能。
以下示例显示如何设置和清除间隔。
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方法。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)