Ahmet Can Güven Ahmet Can Güven - 16 days ago 7
Javascript Question

Javascript: Opening windows in a row problem

this is my html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Something</title>
</head>
<body>
<a href="http://www.google.com">Try Me!</a>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$("a").click(function(event){
for(id=0;id<=10;id++){
setTimeout(function() {
var local_id = id;
window.open("http://www.mysite.com/characterID="+local_id,"", "win"+local_id, "width=100,height=100,resizable");
}, 3000*id);
}
event.preventDefault();
});

</script>
</body>
</html>


This link is opening each window 3 seconds after the next.

This is the row I need:

But it always opens
http://www.mysite.com/characterID=11


How can I fix it?

Thank you...

Answer

This is a common issue.

You're overwriting local_id in the loop, and always referring to the same variable when the code runs. This is because JavaScript does not have block scope, just function scope.

So to scope the id, you need to invoke a function, and define the variable (or function parameter) there.

function createWindow(local_id) {
    setTimeout(function () {
        window.open("http://www.mysite.com/characterID=" + local_id, "", "win" + local_id, "width=100,height=100,resizable");
    }, 3000 * local_id);
}

for (id = 0; id <= 10; id++) {
    createWindow(id);
}

Or a similar patter would be to have the function return a function to the loop.

function createWindow(local_id) {
    return function() {
        window.open("http://www.mysite.com/characterID=" + local_id, "", "win" + local_id, "width=100,height=100,resizable");
    };
}

for (id = 0; id <= 10; id++) {
    setTimeout( createWindow(id) , 3000 * id);
}
Comments