Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause javascript code execution for 2 seconds [duplicate]

Tags:

javascript

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?

like image 664
abdullah sheikh Avatar asked May 18 '13 11:05

abdullah sheikh


People also ask

How do you delay 1 second in JavaScript?

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.

How do you pause a JavaScript script?

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.

How do you stop a run in JavaScript?

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.


2 Answers

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.

like image 171
Khanh TO Avatar answered Oct 05 '22 04:10

Khanh TO


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); 
like image 41
James McLaughlin Avatar answered Oct 05 '22 03:10

James McLaughlin