Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time delay between 2 lines of code in javascript, not settimeout

Tags:

is there a function that would add a time delay between 2 lines of code. Not the settimeout, because settimeout requires a function/object in its arguments.

I am looking for something like this pseudo code

write "abc";
delay(500);
write "xyz";

TIA

Edit: jimr's solution in my other thread worked for my purpose, and so is Robusto's.

I am just wondering why the "sleep" methods given by Robusto and CMS's link are not preferred. How would that be different than the settimeout method since they both introduce a pause in the code? (settimeout pauses before the function is executed, the sleep method pauses before the next line is executed.)

like image 338
Jamex Avatar asked Jun 15 '10 20:06

Jamex


People also ask

What we can use instead of setTimeout in JavaScript?

The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.

How do you delay 2 seconds in JavaScript?

then(() => { console. log("World!"); }); This code will log “Hello”, wait for two seconds, then log “World!” Under the hood we're using the setTimeout method to resolve a Promise after a given number of milliseconds. Notice that we need to use a then callback to make sure the second message is logged with a delay.

How do you make a delay in JavaScript?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.

What is delay () in JavaScript?

Conclusion. setTimeout() is a method that will execute a piece of code after the timer has finished running. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second.


2 Answers

The following is clunky and ugly and I would never do it in my own code and I DO NOT RECOMMEND IT AT ALL, but it shows that such a thing is possible.

// time arg is in milliseconds
function delay(time) {
  var d1 = new Date();
  var d2 = new Date();
  while (d2.valueOf() < d1.valueOf() + time) {
    d2 = new Date();
  }
}
like image 191
Robusto Avatar answered Oct 06 '22 01:10

Robusto


You can use setTimeout so that it almost appears the code runs on two lines:

write('abc')
setTimeout(function() {
write('xyz')
},500)
like image 34
Joel Coehoorn Avatar answered Oct 06 '22 00:10

Joel Coehoorn