Reputation:
I am trying to execute a setInterval function immediately after a button is pressed, then run the function every 5 seconds.
Why does this work:
$(function () {
$('button').on('mousedown', function () {
var checkUser = setInterval(function () {
}, 5000);
checkUser();
});
});
But not this:
$(function () {
$('button').on('mousedown', function () {
var checkUser = setInterval(function () {
}(), 5000);
});
});
Upvotes: 0
Views: 1110
Reputation: 207491
Your first one is not executing a function to start as you think it is. Interval retruns an id, not a reference to the method being called. There should be an error in the console.
The second one is calling the function and storing what the function returns as the interval. In your case it is not returning anything so it is storing undefined.
Store the function, reference it, and call it.
$(function () {
$('button').on('mousedown', function () {
var myFunc = function () {
};
var checkUser = setInterval(myFunc, 5000);
myFunc();
});
});
or use Timeout instead of interval.
$(function () {
$('button').on('mousedown', function () {
var myFunc = function () {
/* do stuff */
setTimeout(myFunc, 5000);
};
myFunc();
});
});
Upvotes: 2