How to delay execution in between the following in my javascript

后端 未结 4 1538
太阳男子
太阳男子 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:22

    You cannot "delay" in JavaScript without locking the browser; i.e the user cannot move their mouse or click anything (undesirable for 3+ seconds!).

    Instead, you should look at setting a timeout, which will execute designated code some time in the future...

    $("#myName").val("Tom");
    setTimeout(function () {
        $("#YourName").val("Jerry");
    
        setTimeout(function () {
            $("#hisName").val("Kids");
        }, 3000);
    }, 3000);
    

    You can check out the documentation for setTimeout here: https://developer.mozilla.org/en/window.setTimeout. The basics of it is that you pass either a function reference, or a string (which should be avoided however), as the first parameter, with the second parameter specifying how many milliseconds the code should be delayed for.

提交回复
热议问题