Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using setTimeout synchronously in JavaScript

I have the following scenario:

setTimeout("alert('this alert is timedout and should be the first');", 5000); alert("this should be the second one"); 

I need the code after the setTimeout to be executed after the code in the setTimeout is executed. Since the code that comes after the setTimeout is not code of my own I can't put it in the function called in the setTimeout...

Is there any way around this?

like image 365
Nathan Avatar asked Nov 08 '10 08:11

Nathan


People also ask

Can you make setTimeout synchronous?

You can also run setTimeout synchronously with await, promise.

Is setTimeout synchronous or asynchronous?

setTimeout is asynchronous - but it does not have a Promise -API. The basic functionality of asynchronous functions is not Promises , but Callbacks (meaning giving a function that gets called asynchronously .

Is setTimeout method works asynchronously?

Working with asynchronous functionssetTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.

What is the alternative for setTimeout in JavaScript?

The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.


2 Answers

Is the code contained in a function?

function test() {     setTimeout(...);           // code that you cannot modify? } 

In that case, you could prevent the function from further execution, and then run it again:

function test(flag) {      if(!flag) {          setTimeout(function() {             alert();            test(true);          }, 5000);          return;      }      // code that you cannot modify  } 
like image 109
David Hedlund Avatar answered Sep 22 '22 03:09

David Hedlund


I came in a situation where I needed a similar functionality last week and it made me think of this post. Basically I think the "Busy Waiting" to which @AndreKR refers, would be a suitable solution in a lot of situations. Below is the code I used to hog up the browser and force a wait condition.

function pause(milliseconds) {  	var dt = new Date();  	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }  }    document.write("first statement");  alert("first statement");    pause(3000);    document.write("<br />3 seconds");  alert("paused for 3 seconds");

Keep in mind that this code acutally holds up your browser. Hope it helps anyone.

like image 39
Nathan Avatar answered Sep 22 '22 03:09

Nathan