ben_aaron
ben_aaron

Reputation: 1532

How to limit query function runs with while looping?

For the last days I've been working on a stimulus presentation function. Now it's the details that need adjustment, in particular im stuck with this: I want my keypress event to be executed only 20 times, after which an alert states that the task is over. I tried for looping and while. I've probably lost the overview to see my fault, but my code doesn't stop after 20 key presses. Where is my mistake?

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

Upvotes: 1

Views: 60

Answers (2)

ndpu
ndpu

Reputation: 22571

You dont need loop, just use global counter, i for example

var i = 0; // saves count of keypress events

$(function() {
    $(document).keypress(function(e) {
        if ($(e.target).is('input, textarea') || i > 20) { // check for 20 events
            return;
        };

        i++; // increase counter...

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

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22415

You need to remove the event when the loop is finished executing, else the event remains attached to the document.

$(document).off("keypress");

Upvotes: 1

Related Questions