如何在setTimeout JavaScript之后触发动作

时间:2015-09-19 10:11:03

标签: javascript jquery html

jsfiddle

我正在使用preLoader()创建一个名为setTimeout()的函数,因为我想让它只运行一次。
preloader()函数完成后,我想隐藏:

<div class="loader">
 <h2 id="loading">0%</h2>
 <h3 id="pleaseWait"></h3>
</div> 

并显示:

<div class="mainContent"></div>

2 个答案:

答案 0 :(得分:1)

这是HTML代码:

<div class="loader">
  <h2 id="loading">0%</h2>
  <h3 id="pleaseWait">pleaswait</h3>
</div> 
<div class="mainContent" hidden="true">ok</div>

JavaScript的:

var executed = false;
setTimeout(function() {
    if(!executed) {//the same of if(executed == false) 
        var loader = document.getElementsByClassName('loader')[0];
        var mainContent = document.getElementsByClassName('mainContent')[0]
        loader.hidden = "true";//hide the loader
        mainContent.removeAttribute("hidden");//show the mainContent
        executed = true;
    }
}, 1000);

答案 1 :(得分:1)

由于您使用的是animate(),因此您不必同时使用setTimeoutsetInterval。只需在动画的complete回调中隐藏/取消隐藏内容。

function preLoader(){
    // animating numbers
    var arrayPleaseWait = ['P','L','E','A','S','E', ' ' , 'W','A','I','T','.','.','.'];
    var searchReturn = '';
    var current = null;
    var wait = $('#pleaseWait');

    $('body').css({
        'backgroundColor':'#E2F7FA'
    });
    $('.mainContent').hide();

    $('#loading').animate({
        someValue: 100
    },{
        duration: 10000,
        easing:'swing',
        step: function() {
            var l = Math.round(Math.round(this.someValue) * (arrayPleaseWait.length-1) / 100) || 0;
            if(current != l){
                searchReturn = searchReturn + arrayPleaseWait[l];
                wait.text(searchReturn + '|');
                current = l;
            }
            $(this).text(Math.round(this.someValue) + '%');
        },
        complete : function(){
            $('.loader').hide();
            $('.mainContent').show();
        }
    });

}

preLoader();

JSfiddle demo