SetTimeout not working, what's wrong?

0

I need this window to open after 3 seconds, but I can not do that by putting the setTimeout right on the button. Whats wrong? :

<script type="text/javascript">
function openWin() {
    var divText = document.getElementById("div-janela").outerHTML;
    var myWindow = window.open('', '',);
    var doc = myWindow.document;
    doc.open();
    doc.write(divText);
    doc.close();
}
</script>
<div id="div-janela">conteudo da div</div>
<input type="submit" onclick="setTimeout(openWin(), 3000)" value="abrir janela">
    
asked by anonymous 28.02.2018 / 16:41

2 answers

0

I changed and put the timeout inside the openWin function, and it worked normally.

<script type="text/javascript">
function openWin() {
    setTimeout(function(){
		var divText = document.getElementById("div-janela").outerHTML;
		var myWindow = window.open('', '',);
		var doc = myWindow.document;
		doc.open();
		doc.write(divText);
		doc.close();
	},3000);
    
}
</script>
<div id="div-janela">conteudo da div</div>
<input type="submit" onclick="openWin()" value="abrir janela">
    
28.02.2018 / 16:46
2

function openWin() {
    setTimeout(function(){
      var divText = document.getElementById("div-janela").textContent = "Abriu :D";
    }, 1000);
}
<div id="div-janela">conteudo da div</div>

<input type="submit" onclick="openWin()" value="abrir janela">

You could use IIFE within the HTML tag

console.log("Ignore o erro");
<h1 onclick="(setTimeout(function(){alert('acho :D');}, 1000))()">Clique</h1>

The problem ...

When the user clicks, he ( onClick() ) immediately calls openWind() , what happens is that you can not put openWin() inside setTimeout() you have to remove the parentheses, it would look something like this. ..

<div id="div-janela">conteudo da div</div>
<input type="submit" onclick="setTimeout(openWin, 3000)" value="abrir janela">

<script type="text/javascript">
function openWin() {
  var divText = document.getElementById("div-janela").outerHTML;
  var myWindow = window.open('', '',);
  var doc = myWindow.document;
  doc.open();
  doc.write(divText);
  doc.close();
}
</script>

Passing openWin without parentheses. The setTimeout() will receive what has to be done and only then will execute the function.

    
28.02.2018 / 16:45