Express App: 如何为每个用户创建一个特定的setTimeout

huangapple go评论73阅读模式
英文:

Express App: How can I create a setTimeout specific to each user

问题

以下是翻译好的部分:

当用户通过向'/signup'发出POST请求注册时,我的想法是创建一个与该特定用户相关联的setTimeout(计时器需要是唯一的)。setTimeout的回调将负责在X分钟内对用户的个人资料进行更改。我还希望存储对此计时器的引用,以便在X分钟内用户在'/delete'路由上删除其帐户之前可以删除它 - 因此需要在路由之间传递对计时器的引用。

这是否可行?如果可以,如何实现?

英文:

The idea is as follows:

When a user signs up by making a post request to '/signup' I want to create a setTimeout relating to that specific user (the timer needs to be unique). The callback (from the setTimeout) will be responsible for making changes to the user's profile in X minutes. I would also like to store a reference to this timer so that it can be deleted should the user delete their account (/delete route) before X minutes has passed - so the reference to the timer needs to be passable between routes.

Is this possible? If so, how can it be achieved?

答案1

得分: 0

我明白你的观点,这里是一个使用全局映射对象实现的简单想法。

const userTimers = new Map();

app.post('/signup', (req, res) => {
  const user = req.body.user;
  const timer = setTimeout(() => {
    //做一些事情
  }, 1000 * 60 * 20);

  // 保存用户的定时器,你可以使用其他键
  userTimers.set(user, timer);

  res.send('success');
});

app.post('/delete', (req, res) => {
  const user = req.body.user;

  if (userTimers.has(user)) {
    const userTimer = userTimers.get(user);
    clearTimeout(userTimer);
    userTimers.delete(user);
  }

  res.send('delete timer');
});

app.listen(3000, () => console.log('监听在3000端口...'));
英文:

I see your point,here is a simple idea implement using a global map object. 

const userTimers = new Map();

app.post('/signup', (req, res) => {
  const user = req.body.user;
  const timer = setTimeout(() => {
    //do some thing
  }, 1000 * 60 * 20);

  // save user's timer, you can use others for key
  userTimers.set(user, timer);

  res.send('success');
});

app.post('/delete', (req, res) => {
  const user = req.body.user;

  if (userTimers.has(user)) {
    const userTimer = userTimers.get(user);
    clearTimeout(userTimer);
    userTimers.delete(user);
  }

  res.send('delete timer');
});

app.listen(3000, () => console.log('listen on 3000...'));

huangapple
  • 本文由 发表于 2023年6月26日 08:21:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552903.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定