这是我的真实项目的代码片段。当我转到'/tracking‘页面时,间隔开始了,这没问题...
但当我转到'/app‘时,interval也在运行。我知道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);发布于 2016-10-05 20:36:35
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路由(不需要重新加载)。但如果没有,你可以删除我已经注释过的部分,因为我认为event close会在重新加载时触发。
https://stackoverflow.com/questions/39873757
复制相似问题