Run Function After Delay

前端 未结 4 847
青春惊慌失措
青春惊慌失措 2021-01-30 01:57

I have the below global jQuery function stored, but on page load, I want to execute it after a 1000 delay. Is there something wrong with my syntax? I know the delay always goes

相关标签:
4条回答
  • 2021-01-30 02:49

    You can add timeout function in jQuery (Show alert after 3 seconds):

    $(document).ready(function($) {
        setTimeout(function() {
         alert("Hello");
        }, 3000);
    });
    
    0 讨论(0)
  • 2021-01-30 02:50

    This answer is just useful to understand how you can make delay using JQuery delay function.

    Imagine you have an alert and you want to set the alert text then show the alert and after a few seconds hide it.

    Here is the simple solution:

    $(".alert-element").html("I'm the alert text").fadeIn(500).delay(5000).fadeOut(1000);
    

    It is completely simple:

    1. .html() will change the text of .alert-element
    2. .fadeIn(500) will fade in after 500 milliseconds
    3. JQuery delay(5000) function will make 5000 milliseconds of delay before calling next function
    4. .fadeOut(1000) at the end of the statement will fade out the .alert-element
    0 讨论(0)
  • 2021-01-30 02:51
    $(document).ready(function() {
    
      // place this within dom ready function
      function showpanel() {     
        $(".navigation").hide();
        $(".page").children(".panel").fadeIn(1000);
     }
    
     // use setTimeout() to execute
     setTimeout(showpanel, 1000)
    
    });
    

    For more see here

    0 讨论(0)
  • 2021-01-30 02:51

    I searched and found the solution in the following URL is better.

    http://www.tutorialrepublic.com/faq/call-a-function-after-some-time-in-jquery.php

    It worth to try.

    It adds your given function to the queue of functions to be executed on the matched element which is currently this.

     $(this).delay(1000).queue(function() {
    
         // your Code | Function here
         
         $(this).dequeue();
      
      });
    

    and then execute the next function on the queue for the matched element(s) which is currently this again.

    -- EDIT [ POSSIBLE EXPLANATION FOR THE DEQUEUE COMMAND ]

    Take a look at the command

    We command the jQuery engine to add a function in internal queue and then after a specific amount of time we command it to call that function, BUT so far we never told it to dequeue it from engine. Right?! And then after every thing is done we are dequeue it from jQuery engine manually. I hope the explanation could help.

    0 讨论(0)
提交回复
热议问题