Javascript: function defined, but Error says. Function not found! (Strange)

This is my code:

function mark() { alert("This is a test box.."); } setTimeout("mark()",5000); 

Error: function sign () not found!

There is another problem .. since it works on http://jsfiddle.net/russcam/6EXa9/ , but it doesnโ€™t work in my application .. so can you help me debug this?

What else could be the reason .. By the way, I am running this inside a GreaseMonkey script!

+6
source share
5 answers

If you use GreaseMonkey, any functions that you define are isolated by GM and are not available in the main window.
However, when you use any of the native functions, such as setTimeout or alert, they are called in the context of the main window, for example; when you call setTimeout you actually call window.setTimeout()

Now the function that you defined, the mark does not exist in the main window, and what you are asking for setTimeout is to evaluate the line "mark ()". When the timeout fires, window.eval( 'mark()' ) is called and, as discussed, window.mark is undefined. Thus, you have several options:

1) Define the label on the window object. GM allows you to do this using the unsafeWindow object as follows:

 unsafeWindow.mark = function(){} setTimeout( 'mark()', 10 ); //this works but is ugly, it uses eval 

2) Pass the link to the local label in setTimeout:

 function mark(){} setTimeout( mark, 10 ); //this works too but you can't send parameters 

But what if you need to send parameters? If you defined your function in the main window, the eval method will work (but it's ugly - don't do this)

 unsafeWindow.mark2 = function( param ) { alert( param ) } setTimeout( 'mark2( "hello" )', 10 ); //this alerts hello 

But this method will work for functions with parameters if you defined them in the main window or just in GM. The call ends with an anonymous function and passed to setTimeout

 setTimeout( function() { mark2( "hello" ) }, 10 ); //this alerts hello 
+11
source

try using this setTimeout(mark,5000);

+5
source

If the only place you need to call the mark function is your timeout, try:

 setTimeout(function() { alert("This is a test box.."); }, 5000); 
+1
source

Two questions:

+1
source

Yes, the Grease Monkey part may matter. Grease Monkey almost certainly terminates your JavaScript in a function so that your JavaScript does not conflict with the JavaScript page.

You use the string form setTimeout , and there is no guarantee what context the string will be executed in, although this is possible globally. Just because your function is visible where you execute setTimeout does not mean that your function will be visible when the line is eval ed.

So, don't use the lowercase form setTimeout (ever), use the Ander.by approach or Walter Ramsby's anonymous functional approach.

0
source

Source: https://habr.com/ru/post/887505/


All Articles