Settimeout not working, what’s wrong?

Asked

Viewed 55 times

0

I need this window to open after 3 seconds, but I’m not getting by putting the setTimeout right on the button. What’s 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">

2 answers

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, it(onClick()) calls the openWind() immediately, what happens is that you cannot put openWin() within the 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 by openWin without the parentheses. The setTimeout() will receive what has to be done and only then will execute the function.

  • Perfect! : Thank you mt!!

  • Damn, it didn’t really work out.. I need to take the contents of the div to that window. tried so: Function openWin() { setTimeout(Function(){var divText = Document.getElementById("div-window").outerHTML; var myWindow = window.open(', ',); var doc = myWindow.Document; doc.open(); doc.write(doc.Text); .close();}, 3000); } did not work..

  • I updated, my answer is not wrong, you must have implemented wrong, because here I did not do your work, I just gave you the notion of how I should do, but in the answer I explain to you what you did wrong (in the question).

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">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.