Engkus Kusnadi Engkus Kusnadi - 3 days ago 3
HTML Question

Javascript if condition not working as expected

I create a script that have a loop action and put a condition where to stop this script. The first

if
is working properly, but not the second one, when I set
maxClick
, the script ignore the
if
condition and continue run the script.

Here's the full of my script



var className = ".link" ;
var delay = 0.1 * 1000 ; //0.1 Seconds
var maxClick = 5;


//Bind event handler
var element = document.querySelectorAll(className);
for (var j = 0; j < element.length; j++) {
element[j].addEventListener('click', function() {
// Optional Function On Click Event
}, false)
}

var i = 0 ;
function change() {
if (i == maxClick ) {
clearInterval(interval);
alert("Clicked Link: " + element.length);
}
if (i == element.length && interval) {
clearInterval(interval);
alert("Clicked Link: " + element.length);
}
element[i++].click();
}

change();
var interval = setInterval(change, delay);

<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>
<a class="link">Link</a>





Here's the fiddle

Answer

It seems like your code runs correctly. When (i == maxClick ) the interval is cleared therefore the second if block does not get executed. I'm assuming you're confused since you're using the same alert value in both blocks. Try doing this instead:

if (i == maxClick ) {
    clearInterval(interval);
    alert("Clicked Link: " + i);
}
Comments