Patrioticcow
Patrioticcow

Reputation: 27058

how to use window.setTimeout with javascript and the module pattern

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

Upvotes: 0

Views: 6101

Answers (2)

dmck
dmck

Reputation: 7861

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)

Upvotes: 4

epascarello
epascarello

Reputation: 207537

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
    };


})();

Upvotes: 1

Related Questions