简体   繁体   中英

How to set a callback function in javascript

I want to excecute function b after the setTimeout function a has finished. I allready know i need a asynchronous callback function for that but have problems to realise that.

setTimeout(function a (){
   element.classList.add('classNameA');
},200);

function b () {
   element.classList.add('classNameB');
}

I tried this one but it doesn't work, what is wrong with that?

setTimeout(function a (b){
   element.classList.add('classNameA');
},200);

function b () {
   element.classList.add('classNameB');
}

EDIT: The function a setTimeout is needed because of an previous transition duration. Function b should get excecuted immediately after function a has done its work.

EDIT: i made my example more clear - i have two different classes i have to add.

setTimeout will in fact call your function after the timeout. Just call your function a() instantaneously and pass b to setTimeout .

Example:

 function a (){
   element.classList.add('className');
 }

 function b () {
   element.classList.remove('className');
 }

 setTimeout(async function (){
   await a();
   b();
 },200); // a is called after 200 milliseconds

Hope that helped!

What about this:

function b() {
   element.classList.remove('className');
}

setTimeout(function a(){
   element.classList.add('className');
   b();
},200);

Or do you need something like this:

setTimeout(function a(){
   element.classList.add('className');
   setTimeout(function b() {
       element.classList.remove('className');
   }, 200);
},200);
 function a (){
   element.classList.add('className');
   setTimeout(b,200);
 }

 function b () {
   element.classList.remove('className');
 }

 a(); 

This calls function a and 200 milliseconds later calls function b

You could use JavaScript Promises to execute function b once function a done executing.

 var element = document.querySelector('.element'); function a() { return new Promise(function(resolve, reject) { setTimeout((function() { console.log('class added'); resolve(element.classList.add('red')); }), 2000); }); } function b() { console.log('class removed..'); element.classList.remove('red'); } a().then(b); 
 .red{ color: red; } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>SetTimeout</title> </head> <body> <span class="element">hello</span> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM