JavaScript Beginner. Why is my Function not Running? (Online JSfiddle Example)

Started by
1 comment, last by Oliver Sch 11 years, 5 months ago
I would like to know why my render(); is running about 60 times per second, while my moveCube(); function is only running once.

They both seem to be in the same Loop. (None)

Here is the example with code:

http://jsfiddle.net/Schoening/ywarw/


And here is the plain code:

[source lang="java"]<script src="https://raw.github.com/mrdoob/three.js/master/build/three.js"></script>[/source]
[source lang="jscript"]var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(50, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var cubePos = 0;

var geometry = new THREE.CubeGeometry(1,1,1);
var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;

function moveCube(){
cube.position.x = cube.position.x +1;

}

function render() {
cube.rotation.x += 0.02; cube.rotation.y += 0.02;
requestAnimationFrame(render);
renderer.render(scene, camera);
}

render();
moveCube();?[/source]
Advertisement
actually u are calling both render and moveCube once, but in your render function u request an AnimationFrame which makes sure that your render function is called 60 times a second.As your moveCube does not request such an AnimationFrame its just called once. You could either fix that by adding an RequestAnimationFrame-call to it or , and this is the way i would do it, by calling moveCube inside your render function. Here is a example how u could do it http://jsfiddle.net/ywarw/2/.

regards glf

ps: if u found this useful feel free to click the "up"-arrow
Thanks !

After I posted this Question I found what it means that JavaScript is Event Based.

So I was waiting for a Loop that would never come :D


As it stands right now, I think I will run Logic via intervals and timeouts. And rendering graphics and animations with the setAnimationFrame.

Objections?

This topic is closed to new replies.

Advertisement