0
<html>
<body>
<a href="" id = "content2">Click Here</a>
<body>
</html>

I am using the following code to check the href attribute of the anchor tag and if it is blank I want to show alert for now. But when I write the code of javaScript in web browser console my complete system ends up unresponsive for quite some time. I might be doing something wrong. Can someone explain me what?

var a = document.getElementById("content2").getAttribute("href");

let i = 0;
while(a.trim().length < 1)
{
     task(i);
}

function task(i) { 
  setTimeout(function() { 
      alert(i); 
  }, 1000 * 10); 
} 
1
  • Why is the idea behind tracking changes over a href?, using while is a no no because it blocks the code execution (is a sync function). Commented May 10, 2020 at 5:39

2 Answers 2

1

Your timeout call seems to be within a while loop which gets called a ton of times. It should be

var a = document.getElementById("content2").getAttribute("href");

let i = 0;

if (a.trim().length < 1) {
  task(i);
}

function task(i) {
  setTimeout(function() {
    alert(i);
    if (a.trim().length < 1) {
      task(++i);
    }
  }, 1000 * 10);
}
<html>
<body>
<a href="" id = "content2">Click Here</a>
</body>
</html>

This runs your loop after each attempt where a.trim().length < 1

Sign up to request clarification or add additional context in comments.

Comments

0

You need change while loop to if condition, the while loop have never ended.

var a = document.getElementById("content2").getAttribute("href");

let i = 0;
if(a.trim().length < 1)
{
     task(i);
}

function task(i) { 
  setTimeout(function() { 
      alert(i); 
  }, 1000 * 10); 
} 
<html>
<body>
<a href="" id = "content2">Click Here</a>
<body>
</html>

2 Comments

But replacing if in place of while will execute the code only once. I want to execute the code every second not just once
but you need change condition of while loop? do you want to loop until what

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.