jeezyfreezy
jeezyfreezy

Reputation: 302

ClearInterval Is Not Stopping

I'm trying to use setInterval to check for hash value change when a person clicks on a submit button. When the submit button is hit, the page will not change at all. Only the hash value is changed. I want to use the setInterval to repeatedly look for the hash value until it goes to page2 (in case the form values entered are incorrect). Once page2 is detected, it will clear the setInterval, but this part is not working.

var chkHash;
var hashval = window.location.hash;

var sb = document.getElementById("submitButton").onclick = function() {
    startHash();
}

function checkHash() {
   hv = window.location.hash;
   if (hashval !== hv ) { hashval = hv; }

   if(/page2/i.test(hv)) {
      clearHash();
   }
}

function startHash() {
   chkHash = setInterval('checkHash()', 5000);
}

function clearHash() {
   clearInterval(chkHash);
}

Upvotes: 1

Views: 1767

Answers (1)

Rob W
Rob W

Reputation: 349082

Some improvements:

//Inside startHash, change:
chkHash = setInterval('checkHash()', 5000);

//to
clearInterval(chkHash); //Don't create multiple timers
chkHash = setInterval(checkHash, 5000);

I also recommend to add var before hv = window.location.hash inside function checkHash, so that the variable doesn't leak to the global scope.

Upvotes: 2

Related Questions