How can i use my rand in window name in the following code :
var rand = 185656;
setTimeout("win+rand+2 = window.open('url'+secid , '_blank')",2000);
+rand+ not work
How can i use my rand in window name in the following code :
var rand = 185656;
setTimeout("win+rand+2 = window.open('url'+secid , '_blank')",2000);
+rand+ not work
Don't pass a string to setTimeout
. Pass a function instead and set your global property explicitly on window
, which will allow you to use square bracket notation:
setTimeout(function () {
window["win" + rand + "2"] = window.open("url" + secid, "_blank");
}, 2000);
The reason for not passing a string to setTimeout
(or setInterval
) is that it's an alias for eval
, which can be dangerous.
What you currently have will generate a reference error. It's effectively like doing this, which is obviously never going to work:
"a" + "b" = "c"; // ReferenceError: Invalid left-hand side in assignment
It must be outside the quotes.
setTimeout("win"+rand+"2 = window.open('url'+secid , '_blank')",2000);
You need to "open" and "close" the String again:
setTimeout("win" + rand + "2 = window.open('url'" + secid + " , '_blank')",2000);
See this article for the very basics.
Apart from that you shouldn't be passing executable code to setTimeout
(it will get eval
'd), use a function reference or an anonymous function to do so.
Also, constructiong var names like this is a bad idea as well. Look into objects and keys for that.
You could do:
setTimeout(function(){
var rand = 185656;
window['win' + rand + '2'] = window.open('url'+secid , '_blank'); //creates a global variable by adding a property to the global object
}, 2000);
Firstly, don't pass strings to setTimeout. Use the callback function instead. Then the variable has to be outside of the string (quotes) to be concatenated:
var rand = 185656;
setTimeout(function() {
window["win" + rand + "2"] = window.open('url'+secid , '_blank');
}, 2000);
May be the quotes is making problem
setTimeout("win"+parseInt(rand)+"2 = window.open('url'+secid , '_blank')",2000);
setTimeout("win" + rand + "2 = window.open('url'+secid , '_blank')",2000);