Hey guys beginningto get my head around JavaScript slowly, just wondering where I am going wrong in this piece of code.
I want ever two seconds for the 'banner' div to flick between hello and bye.
I am going wrong somewhere are it onlyever says hello (tick is always 0)
Any Help Greatly Appreciated
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" > </script>
</head>
<body>
<div id="banner"></div>
<script>
var tick = 0
$(document).ready(
setInterval(change(),2000)
)
function change(){
if(tick == 0){
document.getElementById('banner').innerHTML = "hello"
tick = 1
}
else{
document.getElementById('banner').innerHTML = "bye"
tick = 0;
}
}
</script>
</body>
</html>
You are calling the change
function (so that it runs immediately, with the result passed to setInterval
) instead of passing a reference to the change
function to the setInterval()
function (so that setInterval
can call the change
function itself at the right times).
Try this (passing a reference to change
to setInterval
)
setInterval(change,2000)
instead of this (calling change
and passing the result to setInterval
)
setInterval(change(),2000)
Heres a fiddle: http://jsfiddle.net/5eLktrdf/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments