0

At first, I'm a newbie without experience in node js and would like to learn more. I wrote a delay function and I'm interessted, what you as a javascript professional think about it. What is good or bad on it and why?

I try to write a bot. It has 2 function. Function 1 starts function 2. But function 2 shall not start direct afterwards. It has to start with a delay.

Of course I made research for my topic and have found stuff like this:

How Can I Wait In Node.js (Javascript), l need to pause for a period of time

How to create a sleep/delay in nodejs that is Blocking?

Unfortunately I'm not able to understand and use it. Therefore I made my own try. It works on my computer, but should I bring it on a server?

//function 1 (example)    
function start(){
    ...;
    delay(2500, 'That could be an answer');
}

//Delay
function delay(ms, msg){
  var started = new Date();
  var now;
  var diff = 0;;

  while(diff < ms){  
    now = new Date();
    diff =  now - started;
    console.log('Diff time: '+diff);
  }

  console.log('Delay started at: '+started);
  console.log('Now time: '+now);
  console.log('ms time: '+ms);  
  console.log('While loop is done.');
  answer(msg);  
}

//function 2 (example)
function answer(msg){
...
}

Thank's!

Community
  • 1
  • 1
NewbieXXL
  • 155
  • 1
  • 1
  • 11

3 Answers3

1

This is blocking.. your event loop will block executing this code. No other work will be done throughout the 2500 ms interval except for busy waiting inside the loop.

I'm not sure why you would want to do this. What you can do if you want to start function 2 at some point after function 1 is use setTimeout. This way, function 2 will be started after at least the time that you pass as argument to the setTimeout function while allowing other code to execute and not blocking the node event loop.

setTimeout(function(){
    answer(msg);
}, 2500);
Mostafa Ali
  • 196
  • 1
  • 7
0

it does not work nevertheless. My delay time is more than an hour. Bute function 2 is executed after a couple of seconds.

  setTimeout(function(){
    answer(msg);
  }, Math.floor(Math.random()*1000*87));
NewbieXXL
  • 155
  • 1
  • 1
  • 11
  • How is your delay time more than an hour ? You've got 87000 ms which is 87 seconds multiplied by a value between 0 and 1 all floored ... the maximum timeout you can pass is 87 seconds ... – Mostafa Ali May 27 '16 at 08:31
  • Thanks Mostafa, I was wrong. My problem was indeed my understanding of the conversion of a random number in hours. – NewbieXXL May 27 '16 at 09:34
0

You can use bluebird promises with .delay to maintain your code more clean.

http://bluebirdjs.com/docs/api/promise.delay.html

Make your start function a promise then:

start().delay(2500).then(function (result) {
   // result = start function return statment
});
nada
  • 972
  • 5
  • 22