Subscribe to our RSS

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

Tags:

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:

Hi guys,
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:
jserror

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.

Leave a comment

Your name

September 25, 2016

Spam protection. Enter result of expression you see in the box below.

4 + 10 =