首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >浏览器关闭或Express更改路由时如何在node js中停止间隔

浏览器关闭或Express更改路由时如何在node js中停止间隔
EN

Stack Overflow用户
提问于 2016-10-05 20:18:30
回答 1查看 385关注 0票数 0

这是我的真实项目的代码片段。当我转到'/tracking‘页面时,间隔开始了,这没问题...

但当我转到'/app‘时,interval也在运行。我知道interval是一个全局的东西,由clearInterval(myTimer)关闭,我的问题是,在这种情况下-

如何在更改路线或关闭浏览器时关闭间隔,谢谢,

代码语言:javascript
复制
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);
EN

回答 1

Stack Overflow用户

发布于 2016-10-05 20:36:35

代码语言:javascript
复制
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会在重新加载时触发。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39873757

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档