How can I print the "Hello world" every 2 seconds for 10 seconds in Node.js?

Viewed 16645

I want to print a value (Like Hello world) with interval of 2 seconds till 10 second. How can I do it?

8 Answers

Use setInterval() to print Hello World each 2 seconds, Use setTimeout() to clear the interval after 10 seconds.

var interval = setInterval(function(){ 
  console.log('Hello World'); 
}, 2000);
setTimeout(function() { 
  clearInterval(interval); 
}, 10000);

Code:

var i=0;

var myfunc = setInterval(function(){

    i = i + 1;
    console.log('Hello World at '+ 2*i + ' seconds'); 

    if(i==5) {
        clearInterval(myfunc);
    }

}, 2000);

Output:

Hello World at 2 seconds  
Hello World at 4 seconds  
Hello World at 6 seconds  
Hello World at 8 seconds  
Hello World at 10 seconds  

Use the setTimeout() function to schedule the future execution of a function. The following example works but it is specifically written to make you get a bad evaluation if you use it for carrying out your homework

function myFunc(arg) {
  console.log(`${arg}`);
}

setTimeout(myFunc, 2000, 'Hello world');
setTimeout(myFunc, 4000, 'Hello world');
setTimeout(myFunc, 6000, 'Hello world');
setTimeout(myFunc, 8000, 'Hello world');
setTimeout(myFunc, 10000, 'Hello world');
var noTimeout = 2000;
var newTime = 0;
var maxTime = 10000;

function next(timeout) {
    if (timeout == undefined)
        timeout = noTimeout
    setTimeout(processAuto, timeout);
}

function processAuto() {
    console.log("Hello world")
    newTime = newTime + noTimeout;
    if (newTime >= maxTime) {
        process.exit(0);
    } else {
        next(noTimeout);
    }
}
processAuto();

This gives me an opportunity to play with process.hrtime() method.

let currentTime
let counter = 0

while (counter < 10) {
  if (counter === 0 || currentTime !== (currentTime = process.hrtime()[0])) {
    if (counter++ % 2) console.log("Hello world")
  }
}

Use this snippet for exact interval between each run.

setTimeout(function prn(i){
  console.log('Hello world');
  i++;
  if(i < 5){
    setTimeout(prn, 2000, i);
  }
}, 2000, 0);

and the below one for interval between start of each run.

var inter = setInterval(() => console.log('TCS'), 2000);
setTimeout(() => clearInterval(inter), 10000);
var inter = setInterval(() => console.log('Hello world'), 5000);
setTimeout(() => clearInterval(inter), 10000);
var inter = setInterval(() => console.log('TCS'), 2000);
setTimeout(() => clearInterval(inter), 10000);
Related