setTimeout - how to avoid using string for callback?

后端 未结 2 1317
长发绾君心
长发绾君心 2020-12-09 05:48

When using setTimeout, you have to put the code you want to execute into a string:

setTimeout(\'alert(\"foobar!\");\', 1000);

相关标签:
2条回答
  • 2020-12-09 06:02

    If you don't need to call myGreatFunction with any arguments, you should be able to pass setTimeout a function reference:

    setTimeout(myGreatFunction, 1000);
    

    Also, you should always avoid passing setTimeout code that it needs to evaluate (which is what happens when you wrap the code in quotes). Instead, wrap the code in an anonymous function:

    setTimeout(function() {
        // Code here...
    }, 1000);
    

    See the setTimeout page at the Mozilla Development Centre for more information.

    Steve

    0 讨论(0)
  • 2020-12-09 06:02

    Who said that it doesn't let you do it?

    It does, the code -

    setTimeout(function() { myFunction(); }, 1000);
    

    is perfectly valid.

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