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>
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>
Share
Improve this question
edited May 23, 2017 at 11:52
CommunityBot
11 silver badge
asked Feb 20, 2013 at 16:29
john mangualjohn mangual
8,16813 gold badges58 silver badges96 bronze badges
2 Answers
Reset to default 21You 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.
setInterval accept parametres in quotes:
<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>