ben_aaron
ben_aaron

Reputation: 1522

Insert delay between keypress events and set display time

I'm trying to insert delays in a sequence of stimuli that are presented on the keypress event. The code below shows how I'd tried to insert a 1000ms delay between stimuli (i.e. after the key was pressed, it should take 1000ms before the next stimulus appears). Yet there seems to be no delay. Where am I wrong (is it better to do this with setTimeout)?

And: how could I set the maximum 'display-time' of each stimulus to, say, 2000ms, so that it automatically presents another stimulus even if no key is pressed?

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');
        }
    };
});
});

Upvotes: 0

Views: 366

Answers (1)

attila
attila

Reputation: 2219

According to the documentation for delay: https://api.jquery.com/delay/

The .delay() method is best for delaying between queued jQuery effects.

You should be using setTimeout for this since it also allows you to cancel it. That is really important for your need to have a maximum timeout.

So, first I would break your function up. You could have a function that handles the displaying, which will get called when timeout occurs or when a key is pressed.

$(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);  
    }
});
});

Upvotes: 1

Related Questions