Underscore的油门功能不会触发

时间:2012-12-18 15:41:58

标签: javascript underscore.js

_.throttle(function() {}, 250)功能仅在click上触发吗?因为我试图以一个小延迟运行一些代码,但由于某些原因它似乎没有工作。

return _.throttle(function() {
    return ( $(this).hasClass('dataRevealed') ) ? $(this).addClass('animated fadeOut') : true;
}, 350);

编辑:该功能如下所示:

Application.CardView.prototype.removeSimilarCards = function(_container) {
    return $(_container).find('[data-identifier="card-view"]').each(function() {
        console.log("first");
        _.throttle(function() {
            console.log("inner");
            return ( $(this).hasClass('dataRevealed') ) ? $(this).addClass('animated fadeOut') : true;
        }, 350);
    });
};

3 个答案:

答案 0 :(得分:5)

正如在提到的官方文档underscore#throttle中那样,传入的函数必须是限制版本。你看,"限制"必须在传入之前执行。我只是让它工作。 :) @closure在上面的评论中提到了这个。我们应该更多地阅读官方文件。

var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

答案 1 :(得分:1)

_.throttle用于通过“限制”来阻止函数运行太多次,因此它每X ms只运行一次。您可能希望使用函数队列,在延迟计时器上出列。

这样的事情:

Application.CardView.prototype.removeSimilarCards = function(_container) {
    var $ele = $(_container),
        $cards = $ele.find('[data-identifier="card-view"]');

    $cards.each(function() {
        var $this = $(this);
        $ele.queue('func', function(next){
            if($this.hasClass('dataRevealed')){
                $this.addClass('animated fadeOut');
            }
            setTimeout(next, 350);
        });
    });

    setTimeout(function(){
        $ele.dequeue('func');
    }, 350);

    return $cards;
};

答案 2 :(得分:0)

您的代码中可能还有其他一些问题。

我创建了一个示例,表明它工作正常see example

以下是代码:

var refTime = +new Date();
var fn = _.throttle(function() {
    console.log((+new Date() - refTime)/1000);
}, 3000);

window.setInterval(fn, 10);