Create a custom callback in JavaScript

前端 未结 10 2174
野性不改
野性不改 2020-11-22 08:08

All I need to do is to execute a callback function when my current function execution ends.

function LoadData() 
{
    alert(\'The data has been loaded\');
          


        
10条回答
  •  不思量自难忘°
    2020-11-22 08:42

    Some of the answers, while correct may be a little tricky to understand. Here is an example in layman's terms:

    var users = ["Sam", "Ellie", "Bernie"];
    
    function addUser(username, callback)
    {
        setTimeout(function()
        {
            users.push(username);
            callback();
        }, 200);
    }
    
    function getUsers()
    {
        setTimeout(function()
        {
            console.log(users);
        }, 100);
    }
    
    addUser("Jake", getUsers);
    

    The callback means, "Jake" is always added to the users before displaying the list of users with console.log.

    Source (YouTube)

提交回复
热议问题