Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval( ) -- unexpected identifier - but it works once

Why do I get Uncaught SyntaxError: Unexpected identifier if it works once?

There are a bunch of these on StackOverflow. The punchline is usually a typo somewhere in the script.

It works once, then it gives 1 error message a second.

Here I am changing the colors of states on a map:

<!-- language: lang-js -->
<script type="text/javascript">
colors = [ 'rgba(255,0,0,0.1)','rgba(0,255,0,0.1)','rgba(0,0,255,0.1)'  ];

$(document).ready(function(){

    setInterval(
        $("ul").children().eq( Math.floor(50*Math.random())).css('color', colors[Math.floor(3*Math.random())] )
    ,1000);

});
</script>
like image 555
john mangual Avatar asked Feb 20 '13 16:02

john mangual


1 Answers

You are missing function(){} to wrap your code.

setInterval(function(){
    $("ul").children().eq( Math.floor(50*Math.random())).css('color', colors[Math.floor(3*Math.random())] )
},1000);

it works once because it executes your inner-code looking for a function or string to be returned. When one isn't, it fails with a js error.

like image 98
Kevin B Avatar answered Nov 11 '22 07:11

Kevin B