jQuery jquery延迟代码执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19027090/
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 23:03:19  来源:igfitidea点击:

jquery delay the execution of code

javascriptjquerydate

提问by user1077300

In my jquery function I have a loader gif image. After I show it I want to put a delay for a second and then continue to execute the rest of the code. How can I do that?

在我的 jquery 函数中,我有一个加载器 gif 图像。在我展示它之后,我想延迟一秒钟,然后继续执行其余的代码。我怎样才能做到这一点?

    $('#loader').css('display', '');

    //// I want to put here a delay. 

    var myDate = new Date();
    myDate.setFullYear(2013,8,2);

    var checkyear = myDate.getFullYear();
    var monthly =myDate.getMonth();
    var daily =myDate.getDate();

    $('#day').html(daily) ;
    $('#month').html(months[monthly]) ;
    $('#year').html(checkyear) ;

回答by Paul Rad

Set a timeout like this :

像这样设置超时:

var delay = 1000;
setTimeout(function() {
 // your code
}, delay);

Example http://jsfiddle.net/HuLTs/

示例 http://jsfiddle.net/HuLTs/

回答by GG.

Have you tried .delay?

你试过.delay吗?

$('#loader').show(1).delay(1000).hide(1);

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeoutfunction, which may be more appropriate for certain use cases.

.delay() 方法最适合在排队的 jQuery 效果之间延迟。因为它是有限的——例如,它不提供取消延迟的方法——.delay() 不能替代 JavaScript 的原生 setTimeout函数,后者可能更适合某些用例。

Demo : http://jsfiddle.net/SBrWa/

演示:http: //jsfiddle.net/SBrWa/

回答by coder

$(document).ready(function(){ 
    setTimeout(function(){ 
      //your code
     },
  2000); 
});

Here 2000refers to 2 seconds

这里2000指的是 2 seconds

回答by zahirdhada

You can use this code,

您可以使用此代码,

$('#loader').css('display', '');

setTimeout(function() {
    var myDate = new Date();
    myDate.setFullYear(2013,8,2);

    var checkyear = myDate.getFullYear();
    var monthly =myDate.getMonth();
    var daily =myDate.getDate();

    $('#day').html(daily) ;
    $('#month').html(months[monthly]) ;
    $('#year').html(checkyear) ;
}, 1000);

回答by Rohan Kumar

Try this,

尝试这个,

$(function(){
    $('#loader').css('display', '');
    setTimeout(function(){ 
        var myDate = new Date();
        myDate.setFullYear(2013,8,2);
        var checkyear = myDate.getFullYear();
        var monthly =myDate.getMonth();
        var daily =myDate.getDate();
        $('#day').html(daily) ;
        $('#month').html(months[monthly]) ;
        $('#year').html(checkyear) ;
    },1000);// 1 second delay
});