How to Call setTimeout or setInterval function in an Object’s Method

A common question from JavaScript beginners is how to call the setTimeout or setInterval function. This is an easy task, but can definitely be a headache for those who are new to JavaScript programming. We recently received this question from a user:
I am starting to learn JS but I cant figure out how to call
settimeout inside of the javascript object I created.
Here is my code:
function obj(){
var duration = 3000;
setTimeout(”exec()”, duration);
function exec(){
alert(”exec”);
}
}
obj = new obj();
When I execute the code, I get this error:

…
There are a few ways to call the event, but the most efficient solution to execute setTimeout or setInterval functions in the above code would be to use a non-named function. Below is some quick code for this solution:
... var tmFunc = function(){ exec(); }; setTimeout(tmFunc, duration); function exec(){ alert("exec"); } ...
That’s it ;) Click the Demo button to view this solution in action.






