Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>function clock() { //clock(); /* Remove this recursive call or you'll just get an infinite loop */ var current = new Date(); /* Make sure to use var on variables */ var s = "&lt;p&gt;" + current + "&lt;/p&gt;"; $('#someId').html(s); /* Assuming you want to set 'someId' to 's', not try and append all things that match s to every div */ } var clockStarted = false; $("button").click(function() { if (!clockStarted) /* You only need to set the clock to start once */ setInterval(clock, 1000); /* You only want the interval to start after you've clicked the button and you don't need 'self'. */ clockStarted = true; //clock(); /* Said 'clock;' before */ }); </code></pre> <p>To summarise:</p> <ol> <li><p>When you call a function, you need to call it with parentheses and optionally parameters (e.g. functionName(); instead of functionName). This applies to all JavaScript.</p></li> <li><p>Imagine there is one little gnome happily running through your code. When he gets to a line he reads it and does it. So let's say you've called clock(). He gets there and goes "what now? Oh, I have to go to clock()". So he goes to clock(). He gets there and goes "what now?" Oh, I have to go to clock()". See the pattern? He's going to keep doing this <em>forever</em>, but he never actually gets a chance to do the things that you want clock() to do, because the first thing he sees as soon as he reaches clock() is that he needs to go to clock(). This is called infinite recursion. What you really wanted was to say "every so often I want a little gnome to go to clock() and do the things in there" which is what setInterval does.</p></li> <li><p>$(s).appendTo('div') selects all things that match 's' (which will be nothing) and appends them to all things that match 'div' (which is every div). Instead, you want to select the div with 'someId': "$('#someId')", and append 's' to that: ".append(s);". If you don't want to append but instead replace, you will want to use ".html" not ".append".</p></li> </ol> <h3>Edits</h3> <ul> <li>Includes edits as per request.</li> <li>Includes the fixes to 'setInterval' and 'var time' which slipped past me as per <a href="https://stackoverflow.com/questions/3020692/writing-javascripts-function-using-jquery/3020818#3020818">Anurag's answer</a>. I'm not trying to take credit for these fixes, but just wanted to include as part of a comprehensive answer given the other changes to meet the OP's comment.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload