'Javascript bookmarklet generates "SyntaxError: missing ) in parenthetical" error

I am stumped as to why this simple Javascript bookmarklet fails.

javascript:(setInterval(function() { 
     var element = document.getElementById("observeBtn");
      if (element != null) element.click(); 
}, 1000);)();

The error on the browser console is:

SyntaxError: missing ) in parenthetical

I've counted the parentheses, and they all match (7 left, 7 right).

All this function is supposed to do is check every second for whether the observeBtn button exists on the web page, and if so, automatically press it.

Also, could someone explain what the last "();" is for?



Solution 1:[1]

This works for me:

setInterval(function() { 
    var element = document.getElementById("observeBtn"); 
    if (element != null) element.click(); 
}, 1000);

Edit due to your edit - you don't need the last () that you had.

Solution 2:[2]

If you need to define an IIFE function you need to use its correct sintax:

(function(){
    // code here
})();

or ES6 arrow functions

(() => {
    // code here
})

So your IIFE function should looks like:

(function () {
    setInterval(function() { 

        var element = document.getElementById("observeBtn");
        if (element != null) element.click(); 

    }, 1000);
})();

Note an important aspect of the above code, you define a function and then call it with the last () parenthesis.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xxx
Solution 2