jQuery 如何在javascript中设置时间延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17883692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:09:23  来源:igfitidea点击:

How to set time delay in javascript

javascriptjquery

提问by Blue Orange

I have this a piece of js in my website to switch images but need a delay when you click the image a second time. The delay should be 1000ms. So you would click the img.jpg then the img_onclick.jpg would appear. You would then click the img_onclick.jpg image there should then be a delay of 1000ms before the img.jpg is shown again.

我在我的网站中有一段 js 来切换图像,但是当您第二次单击图像时需要延迟。延迟应为 1000 毫秒。所以你会点击 img.jpg 然后 img_onclick.jpg 会出现。然后,您将单击 img_onclick.jpg 图像,在再次显示 img.jpg 之前应该有 1000 毫秒的延迟。

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();
    });
});

回答by HIRA THAKUR

Use setTimeout():

使用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.

如果您不想这样做setTimeout:请参阅此问题

回答by maudulus

setTimeout(function(){


}, 500); 

Place your code inside of the { }

将您的代码放在 { }

500= 0.5 seconds

500= 0.5 秒

2200= 2.2 seconds

2200= 2.2 秒

etc.

等等。

回答by Ninjaneer

ES-6 Solution

ES-6 解决方案

Below is a sample code which uses aync/awaitto have an actual delay.

下面是一个示例代码,它使用aync/await来实现实际延迟。

There are many constraints and this may not be useful, 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();

回答by Nadir Laskar

There are two (mostly used) types of timer function in javascript setTimeoutand setInterval(other)

javascript 中有两种(主要使用)类型的计时器函数setTimeoutsetInterval其他

Both these methods have same signature. They take a call back function and delay time as parameter.

这两种方法具有相同的签名。它们以回调函数和延迟时间为参数。

setTimeoutexecutes only once after the delay whereas setIntervalkeeps on calling the callback function after every delay milisecs.

setTimeout在延迟后仅执行一次,而setInterval在每次延迟毫秒后继续调用回调函数。

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

这两种方法都返回一个整数标识符,可用于在计时器到期之前清除它们。

clearTimeoutand clearIntervalboth these methods take an integer identifier returned from above functions setTimeoutand setInterval

clearTimeout并且clearInterval这两种方法都采用从上述函数返回的整数标识符setTimeoutsetInterval

Example:

例子:

setTimeout

设置超时

alert("before setTimeout");

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

  alert("after setTimeout");

If you run the the above code you will see that it alerts before setTimeoutand then after setTimeoutfinally it alerts I am setTimeoutafter 1sec (1000ms)

如果您运行上面的代码,您将看到它发出警报before setTimeout,然后在 1 秒(1000 毫秒)后after setTimeout终于发出警报I am setTimeout

What you can notice from the example is that the setTimeout(...)is asynchronous which means it doesn't wait for the timer to get elapsed before going to next statement i.e alert("after setTimeout");

您可以从示例中注意到的setTimeout(...)是,它是异步的,这意味着它在进入下一个语句之前不会等待计时器结束,即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 the above code you will see that it alerts before setIntervaland then after setIntervalfinally it alerts I am setInterval5 times after 1sec (1000ms) because the setTimeout clear the timer after 5 seconds or else every 1 second you will get alert I am setIntervalInfinitely.

如果您运行上面的代码,您将看到它发出警报before setInterval,然后after setInterval最终I am setInterval在 1 秒(1000 毫秒)后发出5 次警报,因为 setTimeout 会在 5 秒后清除计时器,否则每 1 秒您将I am setInterval无限次收到警报。

How browser internally does that?

浏览器内部如何做到这一点?

I will explain in brief.

我将简要说明。

To understand that you have to know about event queue in javascript. There is a event queue implemented in browser. Whenever an event get triggered in js, all of these events (like click etc.. ) are added to this queue. When your browser has nothing to execute it takes an event from queue and executes them one by one.

要了解您必须了解 javascript 中的事件队列。浏览器中实现了一个事件队列。每当在 js 中触发事件时,所有这些事件(如点击等)都会添加到此队列中。当您的浏览器没有要执行的内容时,它会从队列中获取一个事件并一个一个地执行它们。

Now, when you call setTimeoutor setIntervalyour callback get registered to an timer in browser and it gets added to the event queue after the given time expires and eventually javascript takes the event from the queue and executes it.

现在,当您调用setTimeoutsetInterval您的回调注册到浏览器中的计时器时,它会在给定时间到期后添加到事件队列中,最终 javascript 从队列中获取事件并执行它。

This happens so, because javascript engine are single threaded and they can execute only one thing at a time. So, they cannot execute other javascript and keep track of your timer. That is why these timers are registered with browser (browser are not single threaded) and it can keep track of timer and add an event in the queue after the timer expires.

之所以会这样,是因为 javascript 引擎是单线程的,一次只能执行一件事。因此,他们无法执行其他 javascript 并跟踪您的计时器。这就是为什么这些计时器在浏览器中注册(浏览器不是单线程的)并且它可以跟踪计时器并在计时器到期后在队列中添加一个事件。

same happens for setIntervalonly in this case the event is added to the queue again and again after the specified interval until it gets cleared or browser page refreshed.

同样的情况setInterval在这种情况下,直到它被清除或浏览器页面刷新事件添加到队列中一次又一次的指定时间间隔后只。

Note

The delay parameter you pass to these functions is the minimum delay time to execute the callback. This is because after the timer expires the browser adds the event to the queue to be executed by the javascript engine but the execution of the callback depends upon your events position in the queue and as the engine is single threaded it will execute all the events in the queue one by one.

笔记

您传递给这些函数的延迟参数是执行回调的最小延迟时间。这是因为在计时器到期后,浏览器会将事件添加到由 javascript 引擎执行的队列中,但回调的执行取决于您在队列中的事件位置,并且由于引擎是单线程的,它将执行所有事件一一排队。

Hence, your callback may sometime take more than the specified delay time to be called specially when your other code blocks the thread and not giving it time to process what's there in the queue.

因此,当您的其他代码阻塞线程并且没有时间处理队列中的内容时,您的回调有时可能需要超过指定的延迟时间才能被专门调用。

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

正如我所提到的,javascript 是单线程的。所以,如果你长时间阻塞线程。

Like this code

喜欢这个代码

while(true) { //infinite loop 
}

Your user may get a message saying page not responding.

您的用户可能会收到一条消息,说页面没有响应

回答by user1188867

For sync 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;
    }
  }
}

回答by Amir Md Amiruzzaman

Here is what I am doing to solve this issue. I agree this is because of the timing issue and needed a pause 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.

此新代码将暂停 1 秒钟,同时运行您的代码。

回答by oOJITOSo

If you need refresh, this is another posibility:

如果您需要刷新,这是另一种可能性:

setTimeout(function () { 
    $("#jsSegurosProductos").jsGrid("refresh"); 
}, 1000);

回答by oOJITOSo

I'll give my input because it helps me understand what im doing.

我会给出我的意见,因为它可以帮助我理解我在做什么。

To make an auto scrolling slide show that has a 3 second wait I did the following:

要制作一个等待 3 秒的自动滚动幻灯片,我执行了以下操作:

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 executing setTimeout() like this; it will execute all time out functions as if they where executed at the same time assuming that in setTimeout(nextImage, delayTime);delay time is a static 3000 milliseconds.

请记住,像这样执行 setTimeout() 时;假设在 setTimeout(nextImage, delayTime); 延迟时间是静态的 3000 毫秒,它将执行所有超时函数,就像它们同时执行一样。

What I did to account for this was add an extra 3000 milli/s after each for loop incrementation via delayTime += timeIncrement;.

为了解决这个问题,我所做的是在通过delayTime += timeIncrement;.

For those who care here is what my nextImage() looks like:

对于那些关心这里的人来说,我的 nextImage() 是这样的:

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;
    }
}