Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js: how to use setInterval and clearInterval?

Tags:

node.js

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
like image 565
yarek Avatar asked Oct 05 '17 15:10

yarek


People also ask

Can you clearInterval within setInterval?

Calling clearInterval() inside setInterval() has no effect But after calling clearInterval(), it will continue to execute.

Can I use setInterval with Nodejs?

We can use the setInterval() method like this when we need to fetch some information after every fixed interval like when we are building a clock and we need to calculate and update the number of seconds after every second.

Can we use two setInterval in JavaScript?

Good question, but in JS you can't. To have multiple functions in the same program execute at the same time you need multi-threading and some deep timing and thread handling skills. JS is single threaded.


4 Answers

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.

like image 187
Syed Ayesha Bebe Avatar answered Oct 22 '22 16:10

Syed Ayesha Bebe


You can use "this" in the following example:

const dgram = require('dgram');
const message = Buffer.from('from raspberry pi 3');
const client = dgram.createSocket('udp4');
var count = 0;

function intervalFunc() {
  count++;
  client.send(message, 3001, 'localhost', (err) => {
    //client.close();
  });
  if (count == '5') {
    clearInterval(this);
  }
}
setInterval(intervalFunc, 1500);
like image 41
farshad-nsh Avatar answered Oct 22 '22 17:10

farshad-nsh


If you want a JavaScript like interval ID after creating a setInterval timer, you can do the following,

function callbackFunc() {
  console.log("I'm just an example callback function");
}

const timeoutObj = setInterval(callbackFunc, 1000);
const intervalId = timeoutObj[Symbol.toPrimitive](); //intervalId is an interger

// Later you can clear the timer by calling clearInterval with the intervalId like,
clearInterval(intervalId);

Note: This only works when your node version is >= v12.19.0.

like image 5
vicke4 Avatar answered Oct 22 '22 17:10

vicke4


This just caught me. Exactly the same scenario, clearInterval simply wasn't working.

Looking in the console, the result of setInterval was an object, not a number. I was quite confused.

The solution was to remove this import statement, which had snuck in:

import { setInterval } from 'timers';

like image 4
FTWinston Avatar answered Oct 22 '22 16:10

FTWinston