Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 + Jscript with JQuery, setInterval problem

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">

<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.

like image 570
Toby Wilson Avatar asked Dec 20 '25 17:12

Toby Wilson


1 Answers

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.

like image 89
Andy E Avatar answered Dec 22 '25 09:12

Andy E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!