Script open only after specified time

1

I have a script, however it opens as soon as it is loaded. I would like to have it run after 10 seconds and open along with my div, it looks like this:

<div id="mame">
    CONTEUDO
</div>
<script>
    var div = document.getElementById('mame');
    div.style.display = 'none';
    setTimeout(function() {
        div.style.display = 'block';
    }, 10000);
</script>

Is there any method of it not running after loading the site and waiting for those 10 seconds? Thanks

    
asked by anonymous 06.03.2016 / 22:36

2 answers

3

Well I looked here is all correct, it works correctly your code tested in the newest Chorme and in IE 11, maybe the rest of the codes of your page are interfering. But I have caveats to your code that would be:

1) I believe that the CSS property that 'hides' your DIV should be in the element itself, I say this because depending on the browser runtime, appear, and being in the element itself the chance of this occurring is minimal. Then it would look like this:

<div id="mame" style="display: none;">CONTEUDO</div>

2) Depending on how much content there is on your page outside of these codes it may be that the content of the DIV is shown or not displayed at the correct time, so I would check if all content was executed and after that it triggered the 10 second event.

Adding these two observations your code would look like this:

<div id="mame" style="display: none;">CONTEUDO</div>

<script>
window.onload = function() { // Espera tudo ser carregado para executar
 var div = document.getElementById("mame"); // Pega o objeto do elemento DIV

 window.setTimeout(function() { // Inicia a contagem de 10 segundos 
  div.style.display = "";  // Remove a proriedade que esta escondendo a DIV
 }, (10 * 1000)); 
}
</script>
    
06.03.2016 / 22:58
3

One solution is to dynamically add JS to the page.

Click "Run" below, and see a functional demonstration of this code:

var delayedScript =document.createElement('script');

delayedScript.setAttribute( 'type','text/javascript');
delayedScript.setAttribute( 'src','http://codepen.io/tholman/pen/EpfLs.js' );

window.onload = function() {
  var minhaDiv = document.getElementById("mame");
  window.setTimeout( function() {
    minhaDiv .style.display = 'block';
    document.getElementsByTagName("head")[0].appendChild( delayedScript );
  }, 5 * 1000 )
}
Aguarde o Timer...
<div id="mame" style="display:none">
    <canvas id="canvas"></canvas>
</div>

External JS runs only when the timer completes. If you need something more specific, it pays to adjust the JS to have more control, rather than "delay" it.

External JS Credits: Tim Holman

    
06.03.2016 / 23:15