Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sleep/delay/wait function

Tags:

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.

like image 469
user2704237 Avatar asked Oct 15 '13 19:10

user2704237


People also ask

How do you add wait or delay in JavaScript?

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.

How do you sleep for 3 seconds in JavaScript?

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'.

Is there a wait function in JavaScript?

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!”

How do you sleep 5 seconds in JavaScript?

Usage: const yourFunction = async () => { await delay(5000); console. log("Waited 5s"); await delay(5000); console.


1 Answers

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.

like image 101
Deep Avatar answered Sep 21 '22 14:09

Deep