Facing error 'callbacks.js:13 Uncaught TypeError: callback is not a function'

125 Views Asked by At

I am trying to print a message 'Successfully generated 10 numbers' once the numbers till 10 are printed, but facing the issue Facing error 'callbacks.js:13 Uncaught TypeError: callback is not a function' even after i passed callback function in the argument.

callbacks.html:

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>JS - Asynchronous - Callbacks</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>Number generator till 15</h3>
<p id="num"></p>

<h3>Message</h3>
<p id="msg"></p>
<script src="callbacks.js" charset="utf-8"></script>
</body>
</html>

callbacks.js:

var a = setInterval(gen, 1000);
let n = 0;

function gen(callback){
    n = n + 1;
    document.getElementById('num').innerHTML = n;

    if ( n == 10){
        clearInterval(a);
    }

    callback();
}

function printMessage(){
    document.getElementById('msg').innerHTML = 'Succesfully generated 10 numbers';
}

gen(printMessage);
1

There are 1 best solutions below

3
Nicolas Straub On

change var a = setInterval(gen, 1000); to:

var a = setInterval(function () {
    gen(printMessage);
}, 1000);

this will call gen with the callback parameter assigned correctly, in a second-long interval.