HTML5 + Jscript with JQuery, setInterval problem

天大地大妈咪最大 提交于 2019-12-10 20:14:53

问题


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.


回答1:


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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/3725470/html5-jscript-with-jquery-setinterval-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!