在setInterval函数内部使用.call()传递参数

Passing parameters using .call() inside a setInterval function

本文关键字:参数 call setInterval 函数 内部      更新时间:2023-09-26

我要做的是制作一个函数,只要按住鼠标按钮,该函数就会连续调用另一个函数。我这样做只是为了更好地理解.call()和回调。这是我的代码:

jQuery.fn.contmousedown = function(mousedownCallback){
  var interval, self = this;
  jQuery(this).mousedown(function(event){
    interval = setInterval(function(self, event){
      mousedownCallback.call(self, event);
      console.log('on');
    },0);
  });
  jQuery(this).mouseup(function(event){
    clearInterval(interval);
  });
}
$(document).contmousedown(function(e){
  $('#run').html(e.pageX+', '+e.pageY);
});

我收到的错误是:

Uncaught TypeError: Cannot read property 'pageX' of undefined

当然,我收到的是大约每秒300倍。:)如果我将间隔声明行更改为interval = setInterval(function(self){,那么我会以每秒300倍的速度登录到控制台,但我会丢失该事件。所以我的问题是,我该如何制作它,以便回调函数并将事件参数传递给它?

示例-http://jsfiddle.net/ZxKxD/


在回家的路上考虑到这一点,我决定保留这两项活动会很好。这是我的最后一个代码:

jQuery.fn.mousehold = function(mousedownCallback){
  var interval, self = this, move_event;
  jQuery(this).mousemove(function(e){
    move_event = e;
  });
  jQuery(this).mousedown(function(click_event){
    interval = setInterval(function(){
      mousedownCallback.call(self, click_event, move_event);
    },0);
  });
  jQuery(this).mouseup(function(){
     clearInterval(interval);
  });
  jQuery(this).mouseout(function(){
     clearInterval(interval);
  });
}
$(document).mousehold(function(click_event, move_event){
  $('#run').html(click_event.pageX+':'+move_event.pageX+', '
                +click_event.pageY+':'+move_event.pageY);
});

setInterval不会将参数传递给回调,因此请删除selfevent参数。这样做不会"失去"活动。

$.fn.contmousedown = function(mousedownCallback)
{
    var interval,
        self = this;
    $(this).mousedown(function(event)
    {
        interval = setInterval(function()
        {
            mousedownCallback.call(self, event);
            console.log('on');
        }, 0);
    });
    $(this).mouseup(function()
    {
        clearInterval(interval);
    });
}

演示:http://jsfiddle.net/mattball/9veUQ


那么,如何才能不断更新光标位置呢?

使用mousemove捕获事件。

$.fn.contmousedown = function(mousedownCallback)
{
    var interval,
        self = this,
        event;
    $(this).mousemove(function(e)
    {
        event = e;
    });
    $(this).mousedown(function ()
    {
        interval = setInterval(function()
        {
            mousedownCallback.call(self, event);
        }, 0);
    });
    $(this).mouseup(function()
    {
        clearInterval(interval);
    });
};

演示:http://jsfiddle.net/mattball/dVaWS/