Sorry if this question has already been asked here before, I could not find a suitable answer.
I am wanting to create a JavaScript sleep/delay/wait function that I can call anywhere in the script, like jQuery's .delay()
I am not able to use setTimeout, as I have a script that is generated by php, and so am not able to put it into two different functions, with the timeout in the middle. I need to create a function that allows me to do
alert("time started"); sleep(4000); alert("time up");
I really do not want to use jQuery.
let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second. If the delay is omitted from the setTimeout() method, then the delay is set to 0 and the function will execute.
Unfortunately, there is no sleep function like that in JavaScript . If you run test2, you will see 'hi' right away ( setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.
The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console.log("Hello"); setTimeout(() => { console.log("World!"); }, 5000); This would log “Hello” to the console, then make JavaScript wait 5 seconds, then log “World!”
Usage: const yourFunction = async () => { await delay(5000); console. log("Waited 5s"); await delay(5000); console.
You cannot just put in a function to pause Javascript unfortunately.
You have to use setTimeout()
Example:
function startTimer () { timer.start(); setTimeout(stopTimer,5000); } function stopTimer () { timer.stop(); }
EDIT:
For your user generated countdown, it is just as simple.
HTML:
<input type="number" id="delay" min="1" max="5">
JS:
var delayInSeconds = parseInt(delay.value); var delayInMilliseconds = delayInSeconds*1000; function startTimer () { timer.start(); setTimeout(stopTimer,delayInMilliseconds); } function stopTimer () { timer.stop; }
Now you simply need to add a trigger for startTimer()
, such as onchange
.
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