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;
        } else {
            action1Done = false;
        if (!action1Done) {
            setTimeout(checkActionState, 300);

How to pass parameter to setTimeout()

use bind to pass parameter

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

use closure

function work(time){
// if the variables used in the anonymous function change before the timeout,It would works fine as well.

use setTimeout and clearTimeout to delay render

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


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

var timerHandler;
    timerHandler = setTimeout(render,500);
date2019-04-27 13:41:59 Author:JPH
Related Tags:

Leave a Reply

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