Hello, long time no ask

I have this problem... seems to work fine if i put it like this

function cerrarTimeout() {
setTimeout("cerrar()",1400);
}

But i want to pass a variable to cerrar() and it wont work like this

function cerrarTimeout(id) {
setTimeout(cerrar(id),1400);
}

nor like this

function cerrarTimeout(id) {

setTimeout("cerrar("+id+")",1400);

}

even tried this

setTimeout(function cerrarTimeout(id) {
cerrar(id)},1400);

Thanks

Not sure what you are trying to do but how about this...

setTimeout(function(){
    cerrar(id)
},1400);

like this?

//delay
setTimeout(function(){
    cerrar(id)
},1400);


// the actual function
function cerrar (id) {

document.getElementById(id).style.display = "none";

};

And how i call the function with the delay if not have a name?
Just call cerrar() ?

Thanks

The sample above executes the cerrar() method after 1400 milliseconds. I don't understand your question.

Well how i call the function with the delay of 1400 ms, Beacuse if i call it like cerrar(), it wont wait 1400 ms

It just instantly close the div

Member Avatar for stbuchok

All you need to do is think of your order of operations. If you always want cerrar to have a timeout, put the timeout inside the function.

//now if you want to cancel the timeout, you can clearTimeout(timeout)
var timeout = cerrar(id);

// the actual function
function cerrar (id) {
    return setTimeout(function(){
        document.getElementById(id).style.display = 'none';
    }, 1400);
};

Oh, sorry I see what you are saying... well you could wrap that in a function as well.. for example..

<!DOCTYPE html>
<html>
<head>
<script>
 function myFunction(){
   setTimeout(function() { cerrar("Hello") },1400);
 }

 function cerrar(id) {
   alert(id);
 };
</script>
</head>
<body>

 <p>Click the button, then see the alert in 1400 milliseconds.</p>
 <button onclick="myFunction()">Click Me!</button>

</body>
</html>

Very thanks

This is solved but here is the more clean method to pass argument(s) you should know:-

function abc(msg, msg1){
    alert(msg + " | " + msg1);
}

setTimeout(abc, 500, "Hello", " World")

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.