JS Pause Wait

JavaScript do not have a function like pause or wait in other programming languages.

However, JS has setTimeout() function, which can delay an action. Following example will popup an alert 4 seconds after you click the "Test Code" button:

setTimeout(alert("4 seconds"),4000);

You need wait 4 seconds to see the alert.

Let's write a wait function:

function wait(ms)
	var d = new Date();
	var d2 = null;
	do { d2 = new Date(); }
	while(d2-d < ms);

Following example will delay 4 seconds, then popup a confirm box, if the user clicks "OK", popup an alert box, otherwise do nothing:

var c = window.confirm("You like this tutorial?");
if (c) alert("Thank you.");
else alert("OK, you don't like this.");

You need to wait 4 seconds to see the alert box.

Wait and then start execute next line:

var n = calc(2);
function calc(x)
	x = x * 1000 + 67;

You need wait 4 seconds to see the calculation result.

endmemo.com © 2024  | Terms of Use | Privacy | Home