【问题标题】:Insert delay between keypress events and set display time在按键事件之间插入延迟并设置显示时间
【发布时间】:2014-04-20 20:47:18
【问题描述】:

我正在尝试在按键事件上呈现的一系列刺激中插入延迟。 下面的代码显示了我如何尝试在刺激之间插入 1000 毫秒的延迟(即按下键后,下一个刺激出现之前应该需要 1000 毫秒)。然而,似乎没有延迟。我哪里错了(用 setTimeout 做这个更好吗)?

还有:我如何将每个刺激的最大“显示时间”设置为 2000 毫秒,以便即使没有按下任何键,它也会自动呈现另一个刺激?

var stim = [ 
        {name:"WORD1", path:".../pic1.jpg"},
        {name:"WORD2", path:".../pic2.jpg"},
        {name:"WORD3", path:".../pic3.jpg"},
            ]


$(function(){
$(document).keypress(function(e){
    if ($(e.target).is('input, textarea')) {
        return;
    };
    if (e.which === 97 || e.which === 108) {
        if(Math.random() < 0.5) {
            var new_word = stim[Math.floor((Math.random()*stim.length)+1)].name;
            $("#abc").delay(1000).text(new_word);
        } else {
            var new_img =  stim[Math.floor((Math.random()*stim.length)+1)].path;
            $("#abc").delay(1000).empty();
            var prox_img = $('<img id="abcimg" height="300px" width="300px">');
            prox_img.attr('src', new_img);
            prox_img.appendTo('#abc');
        }
    };
});
});

【问题讨论】:

    标签: javascript jquery timeout delay


    【解决方案1】:

    根据文档延迟:https://api.jquery.com/delay/

    .delay() 方法最适合在队列 jQuery 之间进行延迟 效果。

    您应该为此使用 setTimeout,因为它还允许您取消它。这对于您需要最大超时非常重要。

    所以,首先我会分解你的功能。您可以有一个处理显示的函数,当超时或按下某个键时会调用该函数。

    $(function(){
      var to = 0; //this is used to clear your timeout when the user clicks a button
      function showNext() {
        if(Math.random() < 0.5) {
          var new_word = stim[Math.floor((Math.random()*stim.length)+1)].name;
          $("#abc").delay(1000).text(new_word);
        } else {
          var new_img =  stim[Math.floor((Math.random()*stim.length)+1)].path;
          $("#abc").delay(1000).empty();
          var prox_img = $('<img id="abcimg" height="300px" width="300px">');
          prox_img.attr('src', new_img);
          prox_img.appendTo('#abc');
        }
      to = setTimeout(function(){showNext()}, 2000);
    }
    $(document).keypress(function(e){
        if ($(e.target).is('input, textarea')) {
            return;
        };
        clearTimeout(to);
        if (e.which === 97 || e.which === 108) {
          setTimeout(function(){showNext();}, 1000);  
        }
    });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      相关资源
      最近更新 更多