setTimeOut Arrgument Passing

后端 未结 2 450
一整个雨季
一整个雨季 2021-01-21 14:10

In JavaScript I want to use the setTimeOut() function like this



        
相关标签:
2条回答
  • 2021-01-21 14:24

    If you want to use parameters, try this example:

    var x = "OK";
    setTimeout(alertOK.bind(null,x), 3000);
    x = "Would be WRONG";
    console.log("before timeout:", x);
    
    function alertOK(x){
    	console.log("after timeout:",x);
    }

    It also works when in loop (where creating functions is not advisable).

    0 讨论(0)
  • 2021-01-21 14:42

    The best way to do this would be to pass an anonymous function to setTimeout. This anonymous function will be able to access id

    setTimeout(function() { showGrid(id); }, 5000);
    

    Passing a string to setTimeout (instead of a function) is usually considered evil, since the string will be eval'd, and should be avoided.

    Also note that you had a slight typo in your code: the function is setTimeout, not setTimeOut (note the lowercase o)

    EDIT

    Based on your comment, the code would look like this:

    setTimeout(function() { document.getElementById().inerHTML = data; }, 500);
    

    except of course you need to pass some sort of id to document.getElementById

    0 讨论(0)
提交回复
热议问题