Execute a function after X seconds in jquery

痴心易碎 提交于 2019-12-13 04:39:08

问题


Instead of triggering code on click of the element, I want this function to run automatically after 4 seconds. How can I make it possible?

$('a.close,form #okLogin, mask').live('click',function () {
    $('.login-popup').fadeOut(300);
    $('#mask').remove();
    return false;
});

回答1:


$(function(){
setTimeout(function(){
$('.login-popup').fadeOut(300);
                $('#mask').remove();

},4000);
});



回答2:


setTimeout(function () {
   $('.login-popup').fadeOut(300);
   $('#mask').remove();
}, 4000);



回答3:


Use the built in setTimeout() function in JavaScript. For executing a function after a period of time, there is no need to use jQuery:

setTimeout(function () {
    // your function goes here

    $('.login-popup').fadeOut(300);
    $('#mask').remove();
}, 4000); // this number is in milliseconds

References:

  • How JavaScript Timers Work - John Resig weblog
  • window.setTimeout - MDN



回答4:


use setTimeout()

setTimeout(function(){
       $('.login-popup').fadeOut(300);
       $('#mask').remove();
 },4000);



回答5:


setTimeout(function(){
    $('#okLogin').click();
}, 4000);

IMPORTANT live() method is deprecated. use .on()




回答6:


Try this:

$('a.close,form #okLogin, mask').on('click', function () {
    $('.login-popup').fadeOut(300);
    $('#mask').remove();
    return false;
});

$(window).load(function () {
    setTimeout(function () {
        $('#okLogin').triggerHandler('click')
    }, 4000);
});


来源:https://stackoverflow.com/questions/16813672/execute-a-function-after-x-seconds-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!