Is there any JavaScript method similar to the jQuery delay()
or wait()
(to delay the execution of a script for a specific amount of time)?
You can also use window.setInterval() to run some code repeatedly at a regular interval.
why can't you put the code behind a promise? (typed in off the top of my head)
new Promise(function(resolve, reject) {
setTimeout(resolve, 2000);
}).then(function() {
console.log('do whatever you wanted to hold off on');
});
If you really want to have a blocking (synchronous) delay
function (for whatsoever), why not do something like this:
<script type="text/javascript">
function delay(ms) {
var cur_d = new Date();
var cur_ticks = cur_d.getTime();
var ms_passed = 0;
while(ms_passed < ms) {
var d = new Date(); // Possible memory leak?
var ticks = d.getTime();
ms_passed = ticks - cur_ticks;
// d = null; // Prevent memory leak?
}
}
alert("2 sec delay")
delay(2000);
alert("done ... 500 ms delay")
delay(500);
alert("done");
</script>
If you only need to test a delay you can use this:
function delay(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}
And then if you want to delay for 2 second you do:
delay(2000);
Might not be the best for production though. More on that in the comments
The simplest solution to call your function with delay is:
function executeWithDelay(anotherFunction) {
setTimeout(anotherFunction, delayInMilliseconds);
}
The simple reply is:
setTimeout(
function () {
x = 1;
}, 1000);
The function above waits for 1 second (1000 ms) then sets x to 1. Obviously this is an example; you can do anything you want inside the anonymous function.