How to Set Time Delay in JavaScript

How to set time delay in javascript

Use setTimeout():

var delayInMilliseconds = 1000; //1 second

setTimeout(function() {
//your code to be executed after 1 second
}, delayInMilliseconds);

If you want to do it without setTimeout: Refer to this question.

how to add delay in javascript

You can make a very simple queue of tasks to be executed based off promises. Since the promise execution already uses a task queue, you just need to keep a single promise and any time you get a new thing to add, you chain it via .then() and keep the latest promise. That way if you add three tasks T1 -> T2 -> T3, they would resolve in the order they were added. If you add a task that just adds a simple delay between them like T1 -> wait 6 seconds -> T2 -> wait 5 seconds -> T3 then that will run also space out the executions.

This is a sample implementation to illustrate the idea that utilises thunks (functions that take no parameters) as task to delay and execute later.

function abc(elm){
this.$elm = document.querySelector(elm)
this.queue = Promise.resolve();
}

/**
* Uniform way of adding a task for later execution
* @param {Function} task - a thunk to be executed later
* @param {number} [delay=0] time in milliseconds to wait after last task finished before executing this on
*/
abc.prototype.addTask = function(task, delay = 0) {
const waitFor = () => new Promise( res => setTimeout(res, delay) );

this.queue = this.queue
.then(waitFor)
.then(task)
}

abc.prototype.addClass = function (str){
this.addTask(() => this.$elm.classList.add(str));
return this
}

abc.prototype.removeClass = function (str){
this.addTask(() => this.$elm.classList.remove(str));
return this
}

abc.prototype.delay = function (timer){
// add an empty function as a task. If needed this can also do logging or other internal logic
this.addTask(() => {}, timer);
return this
}

function $(str){
return new abc(str);
}

//usage

let x = $('#test').delay(5000).delay(1000).addClass('red');

x.delay(1000)
.delay(1000)
.delay(1000)
.delay(1000)
.delay(1000) //5 seconds
.removeClass('red');
.red {
background-color: red;
color: white;
}
<p id="test">
Bacon ipsum dolor amet hamburger t-bone pork, pastrami sirloin swine corned beef tenderloin frankfurter tail ball tip meatball pork belly spare ribs prosciutto. Bresaola turkey buffalo jowl t-bone biltong burgdoggen cow capicola meatball pastrami boudin alcatra. Bresaola chicken bacon cow, frankfurter meatball hamburger jerky. Shankle capicola chicken leberkas turkey. Ball tip bacon doner kielbasa jerky. Salami picanha chicken bacon, turducken buffalo chislic andouille porchetta tongue shankle prosciutto t-bone. Beef andouille cow pork chop alcatra, turducken ribeye sirloin tail boudin strip steak doner.
</p>

How do I add a delay in a JavaScript loop?

The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.

You may want to use something like this instead:

var i = 1;                  //  set your counter to 1
function myLoop() { // create a loop function setTimeout(function() { // call a 3s setTimeout when the loop is called console.log('hello'); // your code here i++; // increment the counter if (i < 10) { // if the counter < 10, call the loop function myLoop(); // .. again which will trigger another } // .. setTimeout() }, 3000)}
myLoop(); // start the loop

Put a Delay in Javascript

Unfortunately, setTimeout() is the only reliable way (not the only way, but the only reliable way) to pause the execution of the script without blocking the UI.

It's not that hard to use actually, instead of writing this:

var x = 1;

// Place mysterious code that blocks the thread for 100 ms.

x = x * 3 + 2;
var y = x / 2;

you use setTimeout() to rewrite it this way:

var x = 1;
var y = null; // To keep under proper scope

setTimeout(function() {
x = x * 3 + 2;
y = x / 2;
}, 100);

I understand that using setTimeout() involves more thought than a desirable sleep() function, but unfortunately the later doesn't exist. Many workarounds are there to try to implement such functions. Some using busy loops:

function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}

others using an XMLHttpRequest tied with a server script that sleeps for a amount of time before returning a result.

Unfortunately, those are workarounds and are likely to cause other problems (such as freezing browsers). It is recommended to simply stick with the recommended way, which is setTimeout()).

Execute script after specific delay using JavaScript

There is the following:

setTimeout(function, milliseconds);

function which can be passed the time after which the function will be executed.

See: Window setTimeout() Method.



Related Topics



Leave a reply



Submit