Search code examples
javascriptcallbacksettimeout

setTimeout makes the text unidentified


I want to write a code that accepts my string and display it after 4 seconds

I wrote this code to show hi after 4 seconds but instea,d it shows the string right away and after 4 seconds it becomes unidentified. My code is here:

`setTimeout(myMessage, 4000);
function myMessage(message){
const para = document.querySelector('.text');
return para.innerHTML = message;
}
myMessage('hi');`

Solution

  • This undefined value is happening because you are setting myMessage as the callback for your setTimeout function without passing it a message argument. The setTimeout callback does not except any arguments, so when you pass a function in like this:

    setTimeout(myFn, 1000);
    

    It's the same as doing this:

    setTimeout(() => myFn(undefined), 1000);
    

    To fix this, you can change your setTimeout implementation like so:

    setTimeout(() => myMessage('another message'), 4000);
    

    Hope this helps!