Daniel
Daniel

Reputation: 1466

How to trigger an action after setTimeout JavaScript

jsfiddle

I'm creating a function named preLoader() and I'm using setTimeout() cause I want to make it run for one time only.
When the preloader() function finish, I want to hide:

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

and show:

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

Upvotes: 2

Views: 1321

Answers (2)

Artur Filipiak
Artur Filipiak

Reputation: 9157

Since you're using animate(), You don't really have to use both setTimeout and setInterval. Simply hide/unhide content in a complete callback of the animation.

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

Upvotes: 1

WriteYour NameHere
WriteYour NameHere

Reputation: 47

this is the HTML code:

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

Upvotes: 1

Related Questions