How to sleep delay wait between actions in Javascript

How to sleep/delay/wait between actions in javascript

we can use settimeout to check the action states,then to delay between actions.
The javascript setTimeout() allows code to be executed a set time after some trigger.It takes two parameters. First a function to be executed and second after how much time (in ms). It will return a id value ,which can be passed into the clearTimeout() function to clear the timer.

function doJob(anyArray) {

    var action1Done = false;

    function checkAction1State() {
        var state = getAction1State();
        if (state === "Done") {
            action1Done = true;
            action2();
        } else {
            action1Done = false;
        }
        if (!action1Done) {
            setTimeout(checkActionState, 300);
        }
    }
    action1();
    checkActionState();
}

How to pass parameter to setTimeout()

use bind to pass parameter

function work(time){
    console.log(time);
}
// if the variables used in the anonymous function change before the timeout,It would be a problem
setTimeout(function() {
    work(time);
}, 4000)
setTimeout(work.bind(null, time), 4000);

use closure

function work(time){
    console.log(time);
}
// if the variables used in the anonymous function change before the timeout,It would works fine as well.
doWork=function(time,timeout){
    setTimeout(function(){
    work(time);
    },timeout);
}
doWork(time,1000);

use setTimeout and clearTimeout to delay render

Assume when user type a word, It will render on the page.

$("#editor").on("change",function(){
    render();
});

If the user is typing quickly, It will render many times. So we want to delay render,just use setTimeout.

var timerHandler;
$("#editor").on("change",function(){
    if(timerHandler)
        clearTimeout(timerHandler);
    timerHandler = setTimeout(render,500);
});
date2019-04-27 13:41:59 From:www.jquerypluginhub.com Author:JPH
Related Tags:
Comments

Leave a Reply

Your email address will not be published. Required fields are marked *