Stop a timeout function
in this code:
$("a").live("click", function(e) {
e.preventDefault();
setTimeout(function () {
$.get(
"someOtherUrl",
{someVariable: "someValue"},
function(resu开发者_运维知识库lt) {
$(".result").html(render(result));
}
);
}, 1000);
$('a').live("touchmove", function(e) {clearTimeout()});
});
I want to stop the timeout when the user moves his finger on the screen. The thing is that clearTimeout() doesn't work because it is not linked to the timeout. How would I name the timeout and clear it quickly? Am I using the right method?
Save the return value from "setTimeout()" in a variable, and then pass that value to "clearTimeout()" to clear it.
$("a").live("click", function(e) {
e.preventDefault();
var t = setTimeout(function () {
$.get(
"someOtherUrl",
{someVariable: "someValue"},
function(result) {
$(".result").html(render(result));
}
);
}, 1000);
$('a').live("touchmove", function(e) {clearTimeout(t);});
});
Now I would actually write that quite differently; as it is, you're adding a redundant "touchmove" handler on every click. Maybe something like this:
function setupAnchorClicks() {
var timer = null;
$("a").live("click", function(e) {
e.preventDefault();
timer = setTimeout(function() {
// ...
}, 1000);
}).live("touchmove", function() {
clearTimeout(timer);
});
}
setupAnchorClicks();
You'll have to save the handle received from setTimeout (it's a plain integer), and then pass it to clearTimeout as the argument.
var functionToCancel = function() {console.log("hello");}
var timeoutHandle = setTimeout(functionToCancel, 1000);
clearTimeout(timeoutHandle);
精彩评论