jquery setTimeout or setInterval

后端 未结 3 1104
暗喜
暗喜 2021-01-16 17:28

I have the below code with the if condition

if(oldMembership++ <= newMembership) {
    var digit;
    $(\'ul#indexSiteCounterBottom\').empty();

    for(i         


        
3条回答
  •  野的像风
    2021-01-16 18:08

    setTimeout is a function used to delay the execution of a function

    You can use it like:

    var to = setTimeout(function() {
    
        // Your code that will be executed after 500 ms
    
    }, 500);
    

    If you wan to cancel the call before 500ms is elapsed, you can used the to var and call the clearTimout(to). This will cancel the timout and your function will not be run after 500ms.

    setInterval is different from the setTimeout because it will run your function every 500ms without any action. It can be viewed as a scheduler.

    You can use it like:

    var iv = setInterval(function() {
    
        // Your code that will be executed every 500ms
    
    }, 500);
    

    If you want to stop the scheduled process, you can use the iv var and call the clearInterval(iv). This will cancel the qscheduler.

    In your case, you should use setTimeout if you want to keep a hand on each call.

    For example, you could write something like:

    // Launch the task if the main test is ok
    if(oldMembership++ <= newMembership) {
    
        // Empty your main UL
        $('ul#indexSiteCounterBottom').empty();
    
        // Run the first process without timeout
        runProcess(0, 500);
    }
    
    // Run one process
    function runProcess(i, ms)
    {
        // Stop the recursivity when the end of the string is reached
        if (i >= membership.toString().length)
            return;
    
        // Set default value for the digit
        var digit = membership.toString()[i];
    
        // Override the digit if requiered
        if(digit == '_')
            digit = ' ';
    
        // Finally process the digit
        $('ul#indexSiteCounterBottom').append('
  • '+digit+'
  • '); $('ul#indexSiteCounterBottom li:nth-child(3n)').addClass('extra-margin'); // Run the next process in 500ms setTimout(function() { runProcess(i+1, ms); }, ms); }

提交回复
热议问题