I’m writing a psychology experiment in jQuery. I want to write a function that will begin the exercise when the user presses p or q. I have that working:
$(function trial() {
$("body").keydown(function(e) {
if (e.which == 81 || e.which == 80)
{
$(".message").text("exercise begun (timestamp)");
var refreshId = setTimeout(timeout, 2000);
}
});
});
But I’m confused about one thing: this function, trial(), runs automatically. I would like to have to call it, for it to run.
For instance, this function
function timeout(x) {
var x = trialNum
$(".message").prepend("Timeout (Trial " + x + ")<br>");
}
which gets called by trial() behaves itself well, it does not run unless called. I assume this has something to do with the $ symbol, and “scope”? All help appreciated.
Oh! Additionally, one more question. I was trying to make a recursive jQuery function and had a lot of trouble with it. What’s the best way to make a function call itself?
It’s because you’re passing a reference to it into
$()(akajQuery()), which is a shortcut for thereadyfunction and runs when the DOM is loaded.Off-topic: BTW, by doing that, you’re using the function as a right-hand value (like something on the right-hand side of an
=sign). That makes it a function expression. Since you’ve named the function (which is a good thing to do), it’s a named function expression. Those have historically not worked well in various JavaScript implementations. Most current browsers are (now) okay, except IE prior to IE9 which will create two completely separate functions, more here: Double take