简体   繁体   中英

Confusion of callback in JavaScript, Node.js

statusDefault = status.textContent,

setStatus = function(s){
    status.textContent = s;//to set any status

    if(s != statusDefault){
        var delay = setTimeout(function(){
            setStatus(statusDefault);
            clearInterval(delay);
         },3000);
    }
};

setStatus('Testing..');

In the code above, I am not getting how it works. The default status changes to "Testing..", and after 3 seconds, it shows the default one again. I'm confused.

How does it work?

statusDefault = status.textContent,

Copy the content before it is changed, caching it inside JavaScript. This is the default content.

setStatus = function(s){
    status.textContent = s;

When the function is ran, set whatever the first argument is to status 's textContent . Put more simply, it just changes whatever the element's content is when the function is ran.

if(s != statusDefault){

Check that the default value wasn't inputted first.

var delay = setTimeout(function(){
  setStatus(statusDefault);
  clearInterval(delay);
}, 3000);

Create a timeout that lasts 3000 milliseconds (3 seconds), after 3 seconds it calls itself internally again with setStatus(statusDefault) , this will reset the content to whatever it was originally (because of statusDefault ), and it will also render the previous if statement false, so it doesn't create another timeout.

Here is a more brief (and probably easier to understand) list:

  1. The original content is copied into statusDefault .
  2. The content is set to 'Testing..' .
  3. 'Testing..' is not equal to the original content.
  4. Create a timeout that lasts 3 seconds (creating a 3 second delay).
  5. Function calls itself internally again, passing in statusDefault .
  6. The content is set to statusDefault .
  7. If statement is false. No more tasks, JavaScript is done.

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