I’m trying to create a string randomiser with animation but its not working.
I use this function to call the function following a Frame rate that the browser picks:
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback, element){
window.setTimeout(callback, 1000 / 60);
};
})();
Followed by this as my method to generate and display the string:
function create(chars,string_length){
output = [];
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
output.push(randomstring);
document.getElementById('cb').innerHTML = (output.join(''));
}
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var length = 20;
requestAnimFrame( create(chars,length) );
It generates a string to my div ‘id’ but only once – so the function working but it is not being called all the time =/
Why would this be ?
When you’re using requestAnimationFrame it will only run the function once. You need to modify
create()to call requestAnimationFrame on itself again. Also, you are making another mistake: instead of passing the functioncreate()to requestAnimationFrame, you’re actually invokingcreate(chars, length)and then passing the result to requestAnimationFrame. Here’s a version that should work: