Reputation: 5660
In the code below, whenever I click on the submit button, multiple window's open up as it it were in infinite loop. If I uncomment alert, then multiple alerts keep popping like they were in infinite loop. Why could this be happening ?
<html>
<head>
<script type = "text/javascript">
var window;
function moveBy() {
//alert("-- hello ---");
window = window.open("http://www.w3schools.com");
window.moveBy(10, 20);
}
</script>
</head>
<body>
<input type = "submit" value = "moveBy" onclick = "moveBy()"> </input>
</body>
</html>
Upvotes: 1
Views: 1791
Reputation: 2426
Javascript does not support method overloading, so by calling window.moveBy(10, 20);
you are actually basically calling moveBy()
again, resulting in an infinite loop.
Calling a function from itself is called recursion. The linked post is a good read on this topic, and will guide you on where you might want it. But in your case you clearly don't.
Have a read of this article for more detail.
To prevent this from happening, you can rename your moveBy()
function to myMoveBy()
or better openAndMoveBy()
Upvotes: 8
Reputation: 21759
You are creating a recursion (function that calls itself) by calling window.moveBy
inside your moveBy
function without stating a break point or exit case:
function moveBy() {
//alert("-- hello ---");
window = window.open("http://www.w3schools.com");
window.moveBy(10, 20); //recursion, it will call this function over and over again.
}
Maybe what you want is to use another name for your function and call the actual window.moveBy
inside with predefined parameters:
function customMoveBy() {
//alert("-- hello ---");
window = window.open("http://www.w3schools.com");
window.moveBy(10, 20);
}
<input type = "submit" value = "moveBy" onclick = "customMoveBy()"> </input>
Upvotes: 3
Reputation: 129
The problem is that you are calling the function moveBy
inside the funtion moveBy
. Whenever you execute the function you call it again and again ...
Try this:
<html>
<head>
<script type = "text/javascript">
var window;
function moveBy() {
alert("-- hello ---");
window = window.open("http://www.w3schools.com");
//window.moveBy(10, 20);
}
</script>
</head>
<body>
<input type = "submit" value = "moveBy" onclick = "moveBy()"> </input>
</body>
</html>
Upvotes: 1