JavaScript - jQuery interval

后端 未结 5 1099
执笔经年
执笔经年 2020-12-10 04:20

I am using JavaScript with jQuery. I have the following script to alert hi every 30 seconds.

$(document).ready( function() {
    alert(\"hi\");
         


        
相关标签:
5条回答
  • 2020-12-10 04:43

    You could use setTimeout instead and have the callback reschedule itself.

    $(function() {
        sayHi();
    
        function sayHi() {
           setTimeout(sayHi,30000);
           alert('hi');
        }
    });
    
    0 讨论(0)
  • 2020-12-10 04:43

    No, that's not possible with setInterval. You could use setTimeout for example:

    function foo() {
        alert('hi');
        setTimeout(foo, 30000);
    }
    
    $(function() {
        foo();
    });
    
    0 讨论(0)
  • 2020-12-10 04:52

    Well, there probably is a way of doing it in just one call..

    setInterval(
        (function x() {
            alert('hi');
            return x;
        })(), 30000);
    

    Another solution would be to use arguments.callee, but as it is now deprecated, it is generally not recommended to use it.

    setInterval(
        (function() {
            alert('hi');
            return arguments.callee;
        })(), 30000);
    
    0 讨论(0)
  • 2020-12-10 05:05

    Wrap your code in a function. Then, pass the function as a first argument to setInterval, and call the function:

    $(document).ready( function() {
        //Definition of the function (non-global, because of the previous line)
        function hi(){
            alert("hi");
        }
    
        //set an interval
        setInterval(hi, 30000);
    
        //Call the function
        hi();
    });
    
    0 讨论(0)
  • 2020-12-10 05:05
    $(function() {
    
        function heythere() {
            alert('hi');
            setTimeout(heythere,30000);
        }
    
        heythere();
    
    });
    

    If you want it to only run once after 30 seconds, you are looking to use setTimeout not setInterval.

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