How to set time delay in javascript

I have a js part on my website to switch images, but you need a delay when you click the image a second time. The delay should be 1000 ms. So, you click img.jpg, then img_onclick.jpg will appear. Then you click on the image img_onclick.jpg, after which a delay of 1000 ms should appear before img.jpg appears again.

Here is the code:

jQuery(document).ready(function($) { $(".toggle-container").hide(); $(".trigger").toggle(function () { $(this).addClass("active"); $(".trigger").find('img').prop('src', 'http://localhost:8888/images/img_onclick.jpg'); }, function () { $(this).removeClass("active"); $(".trigger").find('img').prop('src', 'http://localhost:8888/images/img.jpg'); }); $(".trigger").click(function () { $(this).next(".toggle-container").slideToggle(); }); }); 
+120
javascript jquery
Jul 26 '13 at 14:13
source share
8 answers

Use setTimeout() :

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

If you want to do this without setTimeout : see this question .

+288
Jul 26 '13 at 14:15
source share
 setTimeout(function(){ }, 500); 

Put your code inside { }

500 = 0.5 seconds

2200 = 2.2 seconds

and etc.

+35
Oct 10 '14 at 19:05
source share

There are two (mostly used) types of timer functions in javascript setTimeout and setInterval ( others )

Both of these methods have the same signature. They take a callback function and a delay time as a parameter.

setTimeout is only executed once after a delay, while setInterval continues to call the callback function after each milisecs delay.

both of these methods return an integer identifier that can be used to clear them before the timer expires.

clearTimeout and clearInterval both of these methods accept the integer identifier returned from the above setTimeout and setInterval functions

Example:

Settimeout

 alert("before setTimeout"); setTimeout(function(){ alert("I am setTimeout"); },1000); //delay is in milliseconds alert("after setTimeout"); 

If you run the code above, you will see that it warns before setTimeout and then, after setTimeout finally, it warns I am setTimeout after 1 second (1000 ms)

From this example, you can notice that setTimeout(...) is asynchronous, which means that it does not wait for the timer to expire before moving on to the next expression, i.e. alert("after setTimeout");

Example:

setInterval

 alert("before setInterval"); //called first var tid = setInterval(function(){ //called 5 times each time after one second //before getting cleared by below timeout. alert("I am setInterval"); },1000); //delay is in milliseconds alert("after setInterval"); //called second setTimeout(function(){ clearInterval(tid); //clear above interval after 5 seconds },5000); 

If you run the code above, you will see that it warns before setInterval and then, after setInterval finally, it warns I am setInterval 5 times after 1 s (1000 ms), because setTimeout clears the timer after 5 seconds, otherwise every 1 second you will be warned I am setInterval Endlessly.

How does the internal browser do this?

I will explain briefly.

To understand what you need to know about the event queue in JavaScript. The browser implements an event queue. Whenever an event is fired in js, all of these events (e.g. click, etc.) are added to this queue. When your browser has nothing to execute, it takes an event from the queue and executes them one after another.

Now, when you call setTimeout or setInterval your callback is registered by the timer in the browser, and it is added to the event queue after a specified time, and finally javascript takes the event from the queue and executes it.

This is because the javascript engine is single-threaded and can only do one thing at a time. Thus, they cannot execute other JavaScript and track your timer. This is why these timers are registered in the browser (the browser is not single-threaded), and it can monitor the timer and add the event to the queue after the timer expires.

the same thing happens for setInterval only in this case, the event is added to the queue again and again at the specified interval until it is cleared or the browser page is updated.

The note

The delay parameter that you pass to these functions is the minimum delay time for making a callback. This is because after the timer expires, the browser adds the event to the queue, which will be executed by the javascript engine, but the execution of the callback depends on your position of the events in the queue, and since the mechanism is single-threaded, it will execute all events in the queue in turn .

Therefore, your callback can sometimes require more than the specified delay time to be called specifically when your other code blocks the thread and does not give it time to process what is in the queue.

And, as I mentioned, javascript is a single thread. So if you block the thread for a long time.

Like this code

 while(true) { //infinite loop } 

Your user may receive a message that the page is not responding .

+9
Jun 02 '17 at 19:49
source share

ES-6 Solution

The following is sample code that uses aync / await for the actual delay.

There are many restrictions, and it can be useless, but just posting here for fun ..

  async function delay(delayInms) { return new Promise(resolve => { setTimeout(() => { resolve(2); }, delayInms); }); } async function sample() { console.log('a'); console.log('waiting...') let delayres = await delay(3000); console.log('b'); } sample(); 
+6
Apr 13 '18 at 9:19
source share

If you need to upgrade, this is another option:

 setTimeout(function () { $("#jsSegurosProductos").jsGrid("refresh"); }, 1000); 
0
Mar 07 '18 at 21:57
source share

I will contribute because it helps me understand what I am doing.

To make an auto-scroll slideshow that lasts 3 seconds, I did the following:

 var isPlaying = true; function autoPlay(playing){ var delayTime = 3000; var timeIncrement = 3000; if(playing){ for(var i=0; i<6; i++){//I have 6 images setTimeout(nextImage, delayTime); delayTime += timeIncrement; } isPlaying = false; }else{ alert("auto play off"); } } autoPlay(isPlaying); 

Remember that when you execute setTimeout () like this; it will perform all the time-out functions as if they were being executed at the same time, assuming that in setTimeout (nextImage, delayTime) the delay time is static 3000 milliseconds.

To do this, I added an additional 3000 milli / s after each to increase the cycle through delayTime += timeIncrement; ,

For those who don't care, here is what my nextImage () looks like:

 function nextImage(){ if(currentImg === 1){//change to img 2 for(var i=0; i<6; i++){ images[i].style.zIndex = "0"; } images[1].style.zIndex = "1"; imgNumber.innerHTML = imageNumber_Text[1]; imgDescription.innerHTML = imgDescText[1]; currentImg = 2; } else if(currentImg === 2){//change to img 3 for(var i=0; i<6; i++){ images[i].style.zIndex = "0"; } images[2].style.zIndex = "1"; imgNumber.innerHTML = imageNumber_Text[2]; imgDescription.innerHTML = imgDescText[2]; currentImg = 3; } else if(currentImg === 3){//change to img 4 for(var i=0; i<6; i++){ images[i].style.zIndex = "0"; } images[3].style.zIndex = "1"; imgNumber.innerHTML = imageNumber_Text[3]; imgDescription.innerHTML = imgDescText[3]; currentImg = 4; } else if(currentImg === 4){//change to img 5 for(var i=0; i<6; i++){ images[i].style.zIndex = "0"; } images[4].style.zIndex = "1"; imgNumber.innerHTML = imageNumber_Text[4]; imgDescription.innerHTML = imgDescText[4]; currentImg = 5; } else if(currentImg === 5){//change to img 6 for(var i=0; i<6; i++){ images[i].style.zIndex = "0"; } images[5].style.zIndex = "1"; imgNumber.innerHTML = imageNumber_Text[5]; imgDescription.innerHTML = imgDescText[5]; currentImg = 6; } else if(currentImg === 6){//change to img 1 for(var i=0; i<6; i++){ images[i].style.zIndex = "0"; } images[0].style.zIndex = "1"; imgNumber.innerHTML = imageNumber_Text[0]; imgDescription.innerHTML = imgDescText[0]; currentImg = 1; } } 
0
Apr 02 '18 at 17:21
source share

Here is what I am doing to solve this problem. I agree that this is due to a synchronization problem, and he needed a break to execute the code.

 var delayInMilliseconds = 1000; setTimeout(function() { //add your code here to execute }, delayInMilliseconds); 

This new code will pause it for 1 second and meanwhile run your code.

0
Jun 21 '18 at 11:39
source share

To synchronize calls, you can use the method below:

 function sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds){ break; } } } 
0
Feb 15 '19 at 4:58
source share



All Articles