Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

node.js: how to use setInterval and clearInterval?

This is my JS in nodeJS :

function test(a, room, seconds) {
    console.log(a, room, seconds);
}

intervalid = setInterval(test, 1000, 'room', 20);
console.log('intervalid', intervalid);

Which returns me the output:

intervalid Timeout {
    _called: false,
    _idleTimeout: 1000,
    _idlePrev: TimersList {
        _idleNext: [Circular],
        _idlePrev: [Circular],
        _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
        _unrefed: false,
        msecs: 1000,
        nextTick: false
    },
    _idleNext: TimersList {
        _idleNext: [Circular],
        _idlePrev: [Circular],
        _timer: Timer { '0': [Function: listOnTimeout], _list: [Circular] },
        _unrefed: false,
        msecs: 1000,
        nextTick: false
    },
    _idleStart: 377,
    _onTimeout: [Function: test],
    _timerArgs: [ 'room', 20 ],
    _repeat: 1000
}

Whereas in simple Javascript it returns a simple INTEGER number

When I attach interval to an existing user object, example :

user.intervalid = setInterval(test, 1000, 'room', 20);

I am not able to clearInterval any more :

clearInterval(user.intervalid); // does not work
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using setInterval()

What if you need to repeat the execution of your code block at specified intervals? For this, Node has methods called setInterval() and clearInterval(). The setInterval() function is very much like setTimeout(), using the same parameters such as the callback function, delay, and any optional arguments for passing to the callback function.

A simple example of setInterval() appears below:

var interval = setInterval(function(str1, str2) {
  console.log(str1 + " " + str2);
}, 1000, "Hello.", "How are you?");

clearInterval(interval);

This is another way when you want to keep only one interval running every minute

function intervalFunc() {
    console.log("Hello!!!!");
     }
    setInterval(intervalFunc,1500);

In the above example, intervalFunc() will execute about every 1500 milliseconds, or 1.5 seconds, until it is stopped . Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...