每100毫秒+1长moused并停在10

时间:2014-01-30 13:25:42

标签: jquery setinterval mousedown

如果用户进行长时间按压并停在10,

,我想每ms添加一个

那样的东西?

$('#bar').mousedown(function(){
   setInterval(function() {
        for(i=1; i<11; i++){
            $('#foo').val(i);
        }
    }, 100);
});

JSfiddle:http://jsfiddle.net/9qeeg/

2 个答案:

答案 0 :(得分:2)

重复一点以避免使用超时和间隔:

var mouse = {
      interval:null, // reference to setInterval
      count: 0       // count
    };

// on mouse down, set an interval to go off every 100 ms. Every
// execution of this interval increases the counter by one.
// however, clear the interval (automatically) after 1000ms (100ms * 10)
$('#bar').on('mousedown', function(){
  // reset count (Can also fetch it from the input box if you'd like)
  mouse.count = 0;
  // establish interval that will run 10 times (with 100ms delay)
  mouse.interval = setInterval(function(){
    // increase count and place new value in the text field
    $('#foo').val(++mouse.count);
    // stop interval automatically when it reaches 10
    if (mouse.count == 10) {
      clearInterval(mouse.interval);
    }
  }, 100);
});

// Stop interval
// bind to the document to if the user's mouse strays from the button
// we still catch the event
$(document).on('mouseup', function(){
  if (mouse.interval){
    clearInterval(mouse.interval);
    mouse.interval = null;
  }
});

http://jsfiddle.net/xjs25/1/

旧版本:

var mouse = {
      interval:null, // reference to setInterval
      timeout:null,  // reference to setTimeout
      count: 0       // count
    };

// on mouse down, set an interval to go off every 100 ms. Every
// execution of this interval increases the counter by one.
// however, clear the interval (automatically) after 1000ms (100ms * 10)
$('#bar').on('mousedown', function(){
  mouse.count = 0;
  mouse.interval = setInterval(function(){
    $('#foo').val(++mouse.count);
  }, 100);
  mouse.timeout = setTimeout(function(){
    clearInterval(mouse.interval);
  }, 100 * 10);
});

// Stop interval
// bind to the document to if the user's mouse strays from the button
// we still catch the event
$(document).on('mouseup', function(){
  mouse.interval && clearInterval(mouse.interval), mouse.interval = null;
  mouse.timeout && clearTimeout(mouse.timeout), mouse.timeout = null;
});

您的更新小提琴:http://jsfiddle.net/9qeeg/5/

答案 1 :(得分:0)

您可以使用clearInterval()并在mouseUp或达到10

时清除它
var intVal = null;
var cnt = 0;
$('#bar').on('mousedown', function () {
    intVal = setInterval(function () {
        $('#foo').val(cnt);
        cnt == 10 ? clearInterval(intVal) : cnt++;
    }, 100);
}).on('mouseup', function () {
    clearInterval(intVal);
    if (cnt == 10) {
        cnt = 0
    }
});

DEMO