views:

152

answers:

2

Please can someone tell me why this isn't working before I defenestrate everything on my desk.

I have the following html document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html"; charset=utf-8 />
    <title>Sample Gauge using JQuery</title>
</head>
<body>
    <canvas id="gauge" width="200" height="200">
    Your web browser does not support HTML 5 because you fail.
    </canvas>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="gauge.js"></script>
</body>
</html>

And gauge.js:

$(document).ready(function () {
    //(canvas gets assigned)

    startRendering();

    function startRendering() {
        setInterval("render();", 1000);
    }

    function render() {
        renderBackground();
        renderNeedle(-172);
    }

    //(Defined functions for rendering a gauge)
});

render() does not get called, but if I change the setInterval line to just 'render()' it does. Also, if I change setInterval() to contain something like "alert('LOL')" then it does work, it just doesn't seem to work with functions I have defined. With or without a semicolon at the end of the function(s) to call makes no difference, nor does prefixing this. to my functions.

I'm trying to get this working so I can start using it to animate the gauge. Can anyone see why it isn't working?

I hate web development.

+2  A: 

Change

    setInterval("render();", 1000);

To

    setInterval(render, 1000);

When you pass a string to setInterval(), the code inside is executed outside of the current scope. It's much more appropriate to just pass the function anyway. Functions can be passed around just like any other variable if you leave the parenthesis off.

Andy E
+1 - Even better.
Castrohenge
Huzzah, thankyou! <Shuts the window>
Toby Wilson
A: 

I'm not sure why using just "render()" doesn't work but using this code will fix the problem.

function startRendering() {
    setInterval(function(){
        render()
    }, 1000);
}
Castrohenge