SetInterval () - unexpected identifier - but it works once

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

There are tons of them on StackOverflow . A punch list is usually a typo somewhere in a script.

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

Here I change the colors of the states on the 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> 
+7
source share
2 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 internal code, looking for a function or string to be returned. When this is not the case, it fails with the js error.

+17
source

setInterval takes parameters in quotation marks:

 <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> 
0
source

All Articles