-1

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?

Ömürcan Cengiz
  • 2,085
  • 3
  • 22
  • 28
lord_nimon
  • 173
  • 9

2 Answers2

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.

xxx
  • 1,153
  • 1
  • 11
  • 23
Bergis
  • 85
  • 7
  • Can you at least tell me what "SyntaxError: missing ) in parenthetical" means? – lord_nimon Oct 25 '19 at 21:05
  • You were trying to set the function up as an IIFE (immediately-invoked function expression), but it was the incorrect syntax to do so which is why it was yelling at you telling you that you were missing a ')'. – Bergis Oct 25 '19 at 21:10
  • If you need to protect the scope of the function and the variables in it, then use a IIFE for this setInterval, but I am not sure the what the context for this code is. – Bergis Oct 25 '19 at 21:27
0

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.

ricardoorellana
  • 2,270
  • 21
  • 35
  • How should that look with the "javascript:" prefix? I tried this: ```javascript:(function () {return setInterval(function() { var element = document.getElementById("observeBtn"); if (element != null) element.click(); }, 1000); })();``` but all it did was erase my page and replace it with the number 4208. – lord_nimon Oct 25 '19 at 21:10
  • What is the final output you are looking for? – ricardoorellana Oct 25 '19 at 21:13
  • Remove the `return`. – Ivar Oct 25 '19 at 21:15