这是我的真实项目的代码片段。当我转到'/tracking'页时,间隔开始,这是ok的…
但是当我去'/app',那么间隔也运行。我知道interval是一个全局的东西,靠近clearInterval(myTimer)
,我的问题是,在这种情况下-
如何在路由改变或关闭浏览器时关闭间隔,谢谢,
var express = require('express');
var app = express();
app.get('/app', function(req, res) {
res.send("this is app page");
});
app.get('/tracking', function(req, res) {
var myTimer= setInterval(function() {
console.log("Tracking Start between 20 second interval")
}, 20000);
res.send('this is a tracking page!');
});
//Lets define a port we want to listen to
const PORT = 3001;
app.listen(PORT);
console.log('Magic happens on port ' + PORT);
var express = require('express');
var app = express();
var timer = null;
app.use(function(req, res, next) {
// remove this line if you are not using HTML5 routing
if(timer) clearInterval(timer);
req.on('close', function() { if(timer) clearInterval(timer) });
next();
});
app.get('/app', function(req, res) {
res.send("this is app page");
});
app.get('/tracking', function(req, res) {
timer= setInterval(function() {
console.log("Tracking Start between 20 second interval")
}, 20000);
res.send('this is a tracking page!');
});
//Lets define a port we want to listen to
const PORT = 3001;
app.listen(PORT);
console.log('Magic happens on port ' + PORT);
像这样的东西可以工作。我不知道你是否使用HTML5路由(没有重新加载)。但你可以删除我已经评论的部分,如果没有,因为我认为事件close
将触发重新加载