jquery - how to use window.setTimeout with javascript and the module pattern - Stack Overflow

i have this example:var myApp = (function() {var inputClick = function() {console.log('inputClick&

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

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

Share Improve this question asked Aug 20, 2012 at 18:49 PatrioticcowPatrioticcow 27.1k76 gold badges221 silver badges340 bronze badges 1
  • 2 you should never pass a string to setInterval or setTimeout. – jbabey Commented Aug 20, 2012 at 18:52
Add a ment  | 

2 Answers 2

Reset to default 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)

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


})();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745065402a4609225.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信