setTimeout在jQuery插件中不起作用

时间:2015-02-02 13:57:14

标签: javascript jquery plugins timeout

我的jQuery插件中的keyup事件附加了一些行为。一切正常,除了在超时立即执行后应该触发的函数。

        //attach keyup event for the searchbox
        self.data('gallery_searchTimeout',null); //to enable a delay on the keypress search event
        $(self).find('.gallery-search').keyup(function(){

            var needle = 'look for me';
            var delay = 2000;

            //if a timer is already set, clear it in favor of our new timer
            if (self.data('gallery_searchTimeout') != undefined) clearTimeout(self.data('gallery_searchTimeout'));

            self.data('gallery_searchTimeout', setTimeout((self.data('search')(self,needle)), delay) );
        });


    var search = function(self,needle) {

        console.log('search called with needle: '+needle);

    };
    self.data('search',search);            

1 个答案:

答案 0 :(得分:1)

将函数传递给setTimeout而不是调用它。

更改

self.data('gallery_searchTimeout', setTimeout((self.data('search')(self,needle)), delay) );

self.data('gallery_searchTimeout', setTimeout(self.data('search').bind(null,self,needle), delay) );

self.data('gallery_searchTimeout', setTimeout(function(){
     self.data('search')(self,needle);
}, delay) );