0

How would I go about making it so the window closes automatically after the timer goes to zero?

Here's the countdown code:

function countDown(){
    seconds--
    $("#seconds").text(seconds);
    if (seconds === 0){
      clearInterval(i);
    }
  }

  var seconds = 5,
      i = setInterval(countDown, 1000);
  • Possible duplicate of [How to close automatically a webpage](http://stackoverflow.com/questions/14621554/how-to-close-automatically-a-webpage) – davidcondrey Mar 02 '16 at 02:09

3 Answers3

0

You should change that from setInterval() to setTimeout().

setTimeout() only executes once after the delay you specify in milliseconds.

Here's the doco: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

Here's an example:

var updateText = function() {
  $("p").text("Text is now updated");
}
setTimeout(updateText, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>This text will be updated after 2 seconds (2000 milliseconds).</p>
Sarhanis
  • 1,577
  • 1
  • 12
  • 19
0

You CANNOT close window. You can however close all windows you opened in the same JSfile.

 var thisiswindow = null;
    function openWindow() {
     thisiswindow = window.open("", "HiImWindow", "width=150, height=75");   // Opens a new window
    }
    openWindow();

    function closeWindow {
     thisiswindow.close();
    }
PVL
  • 577
  • 1
  • 3
  • 12
0

If your window is opened by a parent window, you can close a window from parent. See http://www.w3schools.com/jsref/met_win_close.asp.

A window can't close itself though, see window.close and self.close do not close the window in Chrome.

And a few more suggestions to your codes:

...
seconds-- // better change it to seconds--; always add ;, to avoid unexpected behavior when your code is minified
...
if (seconds === 0) // maybe seconds <= 0 is better, in case seconds can be initialized to negative values by mistake
Community
  • 1
  • 1
Peter
  • 775
  • 1
  • 6
  • 12