0

i have this example:

var myApp = (function() {

    var inputClick = function() {
        console.log('inputClick');
    };

    var loadRecentTimeout = function()
    {
    window.setTimeout("inputClick()",3000);
    };

    return {
      loadRecentTimeout:loadRecentTimeout,
      inputClick:inputClick
    };


})();

myApp.loadRecentTimeout(); // this returns inputClick() undefined

window.setTimeout("myApp.inputClick();",3000); // this one seems to work , but it calls that method only one time and not every 3 seconds

can anyone explain how can i make this code call the inputClick() method every 3 seconds?

thanks

Patrioticcow
  • 26,422
  • 75
  • 217
  • 337

2 Answers2

4

You want to call setInterval instead of setTimeout

var eventInterval = window.setInterval(function () { 
                        myApp.inputClick(); 
                    },3000);

You also should pass your function as a function instead of a string.

If you need to cancel your repeating event you can call clearInterval

clearInterval(eventInterval)
dmck
  • 7,801
  • 7
  • 43
  • 79
  • 3
    NEVER pass a string to setInterval. – jbabey Aug 20 '12 at 18:52
  • there is an unclosed string, what for? the time? – Patrioticcow Aug 20 '12 at 18:57
  • While I generally agree with @jbabey that is is preferable to pass a function to setInterval/setTimeout, in this case a hard coded string would be safe. What you should NEVER do is pass a string that contains user input to setInterval/setTimeout. – dmck Aug 20 '12 at 18:58
1

When you use a string "functionName()" it evals it in window scope. Instead, assign a reference to the function with just using the name. setTimeout only fires once, you want to use a setInterval.

var myApp = (function() {

    var inputClick = function() {
        console.log('inputClick');
    };

    var loadRecentTimeout = function()
    {
        window.setInterval(inputClick,3000); 
    };

    return {
      loadRecentTimeout:loadRecentTimeout,
      inputClick:inputClick
    };


})();
epascarello
  • 204,599
  • 20
  • 195
  • 236