node.js: how to use setInterval and clearInterval?

后端 未结 3 1713
我寻月下人不归
我寻月下人不归 2020-12-16 12:00

This is my JS in nodeJS :

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

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


        
相关标签:
3条回答
  • 2020-12-16 12:34

    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';

    0 讨论(0)
  • 2020-12-16 12:38

    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.

    0 讨论(0)
  • 2020-12-16 12:48

    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);

    0 讨论(0)
提交回复
热议问题