Storing the return value of node.js setTimeout in redis

后端 未结 3 1169
礼貌的吻别
礼貌的吻别 2021-02-13 09:48

I\'m using setTimeout in Node.js and it seems to behave differently from client-side setTimeout in that it returns an object instead of a number. I wan

3条回答
  •  再見小時候
    2021-02-13 10:36

    You cannot store the object in Redis. The setTimeout method returns a Handler (object reference).

    One idea would be to create your own associative array in memory, and store the index in Redis. For example:

    var nextTimerIndex = 0;
    var timerMap = {};
    
    var timer = setTimeout(function(timerIndex) {
        console.log('Ding!');
    
        // Free timer reference!
        delete timerMap[timerIndex];
    }, 5 * 1000, nextTimerIndex);
    
    // Store index in Redis...
    
    // Then, store the timer object for later reference
    timerMap[nextTimerIndex++] = timer;
    
    // ...
    // To clear the timeout
    clearTimeout(timerMap[myTimerIndex]);
    

提交回复
热议问题