与setInterval和未定义的参数的麻烦 [英] Trouble with setInterval and undefined arguments

查看:264
本文介绍了与setInterval和未定义的参数的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用canvas元素在浏览器中创建一个基本的闪光灯。我期望setInterval继续调用changeBG函数更改为随机背景颜色。这个函数本身工作正常,但不是由setInterval调用。我试图拉起这个页面在firebug,它告诉我,颜色是未定义的。这是有问题的代码。

I'm trying to create a basic strobe light in the browser using the canvas element. I'm expecting setInterval to keep calling the changeBG function to change to a random background color. This function works fine on its own, but not when called by setInterval. I tried pulling up this page in firebug and it told me that colors was undefined. Here's the problematic code.

<html>
<head>
    <title>Strobe!</title>
    <link rel="stylesheet" type="text/css" href="reset.css" />
    <script type="text/javascript">
        function changeBG(colors,ctx,canvas) {                
            ctx.fillStyle = colors[Math.floor(Math.random()*colors.length)]
            ctx.fillRect(0,0,canvas.width,canvas.height)
        }

        function eventLoop() {
            var colors = ['#000000','#ff0000','#00ff00','#0000ff','#ffff00','#ff00ff','#00ffff']
            var canvas = document.getElementById('mainCanvas')
            var ctx = canvas.getContext('2d')
            canvas.width = window.innerWidth
            canvas.height = window.innerHeight
            //changeBG(colors,ctx,canvas)
            setInterval("changeBG(colors,ctx,canvas)", 1000);               
        }
    </script>
</head>
<body onload="eventLoop()">
    <canvas id="mainCanvas" width="800" height="600">
    </canvas>
</body>

所以任何洞察什么是如此将被高度赞赏。

I'm new to javascript so any insight what so ever would be highly appreciated.

推荐答案

如果你没有传递一个字符串到setInterval,你的代码会工作。因为它是在一个字符串,它不能创建一个闭包的变量你试图使用。

You code would work if you weren't passing a string to setInterval. Because it is in a string, it can't create a closure on the variables you are trying to use.

尝试这样:

setInterval(function() {
    changeBG(colors,ctx,canvas);
}, 1000)​;​

使用此方法,将匿名函数传递给setInterval。

Using this method, you are passing an anonymous function to setInterval. It will call this function once per interval, which is 1000 miliseconds in this example.

函数可以使用颜色,ctx和canvas变量,因为它们存在于范围内其中函数被声明。这创建一个闭包,使得这些变量仍然存在(就我们的匿名函数而言),当它被反复调用时。

The function can use the colors, ctx, and canvas variables because they exist in the scope where the function is declared. This creates a closure so that those variables still exist (as far as our anonymous function is concerned) when it is called over and over again.

现在,你可以使用这个代码。为了进一步了解,我建议研究匿名函数和闭包。

For now, you can probably just use this code. For further understanding, I suggest researching anonymous functions and closures.

这篇关于与setInterval和未定义的参数的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆