This function is running continuously without initiating a loop.
The setTimeout is to allow the refreshTags function to run.
I’m sure it’s not the best-written script – I’m no guru – but any ideas on why this script is running in an endless loop?
function addTag()
{
console.log('running');
refreshTags();
var t = document.getElementById('existingTags').textContent.match(/tag1/);
var u = 'tag1';
if (t == u) {alert('This ticket has already been resolved by our team.')};
if (t != u)
{
refreshTags();
setTimeout(function()
{
document.getElementById('tagToAdd').value = 'tag1';
document.getElementById('tagSubmit').click();
alert('Ticket resolved!');
}, 2000)
};
}
Edit: code calling addTag below.
var resolveButton = document.createElement("a");
resolveButton.href = '#';
resolveButton.innerHTML = '<span>Resolve</span>';
resolveButton.setAttribute("onClick", "addTag()");
resolveButton.setAttribute("type", "button");
resolveButton.setAttribute("class", "button1");
var cha = document.getElementById('chatter_view');
cha.parentNode.insertBefore(resolveButton, cha);
Instead of trying to answer why this particular piece of code has an infinite loop, I’ll attempt to answer the bigger question “How do you prevent and debug infinite loops?”.
One of the best defenses I’ve found is to structure your code so control is always flowing in one direction. You have a number of different layers here:
A simple fix to keep your code flowing in one direction is to create dedicated event handlers, e.g.
resolveButtonOnclick() { addTag() }. resolveButtonOnclick is only ever called from the resolveButton’s onclick handler. This makes it much easier to audit your code. You’ve already put aconsole.log('running')at the top of your addTag() function. Now, if you put a console.log() in resolveButtonOnclick() you’ll know right away if the onclick handler is included in your infinite loop.We can’t see your code, but if refreshTags() calls addTag() you would have a circular control flow — these aren’t always bad, but you need to be extra careful that they terminate at some point.
The biggest circular control flow you may have is that addTag() is calling back into the DOM with the .click() method. It would be better, faster and cleaner to submit the form directly from the Javascript or use an XHR.
To debug this loop, you are one the right track with the console.log()s. Add more of them (e.g. every place you call addTag()) and figure out where it is being called from. The other thing you could try is using Chrome’s DevTools: add a ‘debugger;’ call to the top of addTag() and examine the stack trace.