Pierrick Flajoulot Pierrick Flajoulot - 2 months ago 34
Javascript Question

setTimeout - Internet Explorer

I try to make a setTimeout on IE9 but it still throwing a "Invalid argument" Exception...

Here is my code :

var timeout;
timeout = setTimeout((function(s_text){
alert(s_text);
})('Hello'), 1000);


Does anyone has a clue ?

Answer

The approach you are implementing is not going to work. You are using an IIFE that will execute immediately:

(function(s_text){
    alert(s_text);
})('Hello')

And 'Hello' will be alerted. But then, since that method doesn't return anything, then you are calling the timeout with nothing.

timeout = setTimeout(/*undefined or null*/, 1000);

So that's the issue.

edit: If you want to use a variable that already exists outside of the scope, as long as it is defined in a parent scope that the function can see you can use it directly:

var timeout;
var alert_text = "hello";
timeout = setTimeout(function(){
    alert(alert_text);
}, 1000);