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.)
The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.
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.
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.
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.
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();
}
}
You can use setTimeout so that it almost appears the code runs on two lines:
write('abc')
setTimeout(function() {
write('xyz')
},500)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With