1

ボタンをクリックしてから 5 秒後に OK 文字列のポップ ウィンドウが表示されると思いますが、ボタンをクリックするとすぐにポップ ウィンドウが表示されます。なぜですか?

ありがとう!

<html>
<head>
    <title>Wake up call</title>
    <script type="text/javascript">
        function wakeUpCall() { // Function is defined here
            setTimeout(aa("ok"), 5000);
        }

        function aa(bb) {
            alert(bb);
        }
    </script>
</head>
<body bgcolor="lightblue">
    <form>
        <input type="button"
            value="Wake me"
            onclick="wakeUpCall()">
    </form>
</body>
</html>
4

4 に答える 4

2

あなたはそれを間違った方法でやろうとしています。

setTimeout:のコールバックを使用する必要があります

setTimeout(function()
{
    // actual code here
}, 5000);

マイクは彼の答えで-あなたは評価可能な文字列を使うことができると提供しました:

setTimeout('/* actual code here */', 5000);

ただし、これは強くお勧めしません。彼の他の例を使用してください。コールバック関数を参照として渡し、コールバック引数を呼び出します。ただし、コールバック引数を使用する場合は、MDN記事のこのセクションを参照してください。コールバック引数は、すべてのブラウザでサポートされているわけではありません。

個人的には、古いコールバックを使用することをお勧めします。これは、setTimeoutが使用される方法であるためです。

ご参考まで:

スニペットが機能しない理由は、次の理由によるものです。

setTimeout(aa('ok'), 5000);
// aa('ok') here is executed, and returns its value, so, in the end, you pass the returned value of aa inside the Timeout.
// and, nor alert alert, nor your function have a "return" statement, so they both will  return always undefined.
// that translates to:

setTimeout(undefined, 5000); // and, that does nothing
于 2012-11-21T07:31:09.770 に答える
2
function wakeUpCall() { // Function is defined here
            setTimeout(function(){ alert("ok");}, 5000);
        }
于 2012-11-21T07:34:41.147 に答える
1

次のようにするとどうなりますか。

<html>
<head>
    <title>Wake up call</title>
    <script type="text/javascript">
        function wakeUpCall() { // Function is defined here
            setTimeout('aa("ok");', 5000);
        }

        function aa(bb) {
            alert(bb);
        }
    </script>
</head>
<body bgcolor="lightblue">
    <form>
        <input type="button"
            value="Wake me"
            onclick="wakeUpCall()">
    </form>
</body>
</html>

setTimeout 関数で実行するステートメントを引用していることに注意してください。これらの引用符があなたを混乱させるなら、これは見てみるのに良いリソースだと思います: https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout

上記のリソースから学んだ別の方法は次のとおりです。

function wakeUpCall() { // Function is defined here
    setTimeout(aa, 5000, "Your tekst here");
}
于 2012-11-21T07:18:38.643 に答える
1

これには無名関数を使用します。

<html>
<head>
    <title>Wake up call</title>
    <script type="text/javascript">
        function wakeUpCall() { // Function is defined here
            setTimeout(function(){aa("ok");}, 5000);
        }

        function aa(bb) {
            alert(bb);
        }
    </script>
</head>
<body bgcolor="lightblue">
    <form>
        <input type="button"
            value="Wake me"
            onclick="wakeUpCall()">
    </form>
</body>
</html>
于 2012-11-21T07:20:03.140 に答える