I want to stop execution for 2 seconds. So is this, but now follows a code block:
<html> <head> <title> HW 10.12 </title> <script type="text/javascript"> for (var i = 1; i <= 5; i++) { document.write(i); sleep(2); //for the first time loop is excute and sleep for 2 seconds }; </script> </head> <body></body> </html>
For the first time loop is excute and sleep for 2 seconds. I want to stop execution for two seconds?
To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.
JavaScript do not have a function like pause or wait in other programming languages. setTimeout(alert("4 seconds"),4000); You need wait 4 seconds to see the alert. wait(4000); var c = window.
Currently there is no standard way to completely terminate JavaScript. If you need to stop the whole JS process for debugging purposes, use the Developer Tools in Webkit or Firebug on Firefox to set breakpoints by doing debugger; . This will halt absolutely everything from executing.
Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread. setTimeout
is a way to get around this by posting an event to the queue to be executed later without blocking the thread. But if you want a true sleep function, you can write something like this:
function sleep(miliseconds) { var currentTime = new Date().getTime(); while (currentTime + miliseconds >= new Date().getTime()) { } }
Note: The above code is NOT recommended.
There's no (safe) way to pause execution. You can, however, do something like this using setTimeout:
function writeNext(i) { document.write(i); if(i == 5) return; setTimeout(function() { writeNext(i + 1); }, 2000); } writeNext(1);
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