How to delay execution in between the following in my javascript

后端 未结 4 1531
太阳男子
太阳男子 2020-12-03 20:38

I want to delay execution in betwen the follwoing codes:

$(\"#myName\").val(\"Tom\");
///delay by 3s
$(\"#YourName\").val(\"Jerry\");
//delay by 3s

$(\"#his         


        
4条回答
  •  春和景丽
    2020-12-03 21:03

    If delay is always the same (3s in your example), you may avoid nested code and use setInterval instead of setTimeout:

    var i
      , ids = ["myName", "YourName", "hisName"]
      , names = ["Tom", "Jerry", "Kids"];
    
    i = setInterval(function () {
        if (ids.length > 0) {
            $("#" + ids.shift()).val(names.shift());
        } else {
            clearInterval(i);
        }
    }, 3000);
    

提交回复
热议问题