我有一個複選框,我只想保持檢查7秒,然後取消選中它自己。我將以下代碼放在一起,但儘管嘗試清除超時,但如果用戶在切換上單擊幾次,似乎會干擾切換。jQuery timout函數干擾切換
任何人都可以幫助我找到一個更乾淨的方式來做到這一點,如果用戶點擊太頻繁不會錯誤行爲?
$('input#foo').on('change', function(){
clearTimeout(timeout);
if ($(this).is(':checked')) {
$('#box').addClass('splash').stop();
$("div.title").html('Hide thing');
var timeout = setTimeout(function() {
if ($('input#foo').is(':checked')) {
$('input#foo').prop('checked', false).change();
}
}, 7000);
}
else {
$('#box').removeClass('splash').stop();
$("div.title").html('Reveal thing');
}
});
超時的* scope *僅在on-change函數中。將'var timeout ='移動到'$(「input#foo」)。on(「change ...')之前,每次調用on-change函數時,超時值都會爲空,你可以用一個簡單的' console.log(timeout)'infront of cleartimeout –