Let's I will explain why it hadn't worked with your code.
The setInterval
method takes 2 params, the function you want to run and delay
of next execution in milliseconds.
When you call the function with parentheses like syntax()
it will give you the function output i.e
In below code the sum
function does summation of 2 numbers and showing it in span
element.
Basically return
statement stops function execution and gives output.
function sum(a, b) {
return a + b
}
// will print 3;
let sumDiv = document.getElementById('sum');
sumDiv.innerHTML = sum(1, 2);
The sum is <span id='sum'></span>
If you don't have return
statement, the function automatically will return undefined
.
In the below code I am doing addition of 2 numbers, but not returning them and function returns undefined
.
function sum(a, b) {
a + b
}
// will print 3;
let sumDiv = document.getElementById('sum');
sumDiv.innerHTML = sum(1, 2);
The sum is <span id='sum'></span>
Let's return to setInterval
and to our syntax
function.
When you call setInterval(syntax(), 500)
, your syntax()
function executes and returns undefined
as setInterval
first argument function.
You just need to pass your syntax
function without calling.
setInterval(syntax, 500)
The above code will work, because you are just passing your function to be executed each 500
milliseconds, instead of it's returned value which is undefined
and will cause wrong behavior.
You can read more about undefined
type and return
statement here and here respectively. They are very important parts of JavaScript and I suggest you to spend little bit time to read about them.