简体   繁体   中英

how do I assign a variable if

How do I write "assign a variable if a action happens". I'm writing the following but it always returns 1. Thank you

function openwindow(){
testWindow = window.open("popup.php");
setTimeout(function() { testWindow.close(); },1000);
if(testWindow !== null){
    var t = 1;
    return t;
}
}

Try this:

if(testWindow != null){

Sorry, wrong. What are you doing? Of course it always return 1. But what do you want to achieve? setTimeout will be "set" and then instantly the next row of source code will be executed, so what do you expect?

What do you want to do? You're testing the open function, browser everytime opens a window, so return "1" is OK, isn't it?

NB: Better way to write your condition is:

if (testWindow != null) {
  return 1;
} else {
  return 0;
}

or simpler:

return (testWindow != null) ? 1 : 0;

Assuming you want global variable t to be 1 while the window is open and 0 when it's closed after one second, here is better code:

var t = 0;
var testWindow = 0;
function openwindow() {
   t = 1;
   testWindow = window.open("popup.php");
   window.setTimeout(function() { testWindow.close(); t = 0; }, 1000);
}

The testWindow variable is an object and will not be != null when the window is closed. You should use the testWindow.closed property instead. However, as @Tim and @Shadow Wizard pointed out, the timeout will fire after your code has executed.

Depending on what you want to do - you can check the window state as follows:

var testWindow;// declared here so we can access it from outside the function.

function openwindow() {
   testWindow = window.open("popup.php");
   window.setTimeout(function() { testWindow.close(); }, 1000);
}

if (!testWindow) {
    alert('testWindow hasnt been created by openwindow yet');
}

if (testWindow && !testWindow.closed) {
    alert('testWindow is open');
}

if (testWindow && testWindow.closed) {
    alert('testWindow is closed');
}

This will also work if the user closes the window before you do.

UPDATED:

Just to clarify - and forgive me if you get this already.

What setTimeout does is says:

"execute this given function in a second, but meanwhile carry on executing the rest of this code" .

So your function will finish executing as if that setTimeout didn't exist. Later on (after 1 second) the function in the setTimeout will fire.

Hope that's useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM