What is the purpose of Deferred Object in jQuery? [duplicate]

2

I'm studying some jQuery and found this interestingly.

The problem is that I do not quite understand.

What is the purpose of Deferred Object in jQuery?

How can this become useful for jQuery?

    
asked by anonymous 26.10.2015 / 17:34

1 answer

1

What's the use?

It server for processing asynchronous processing. For example:

   var timer;
(function process() {
$('#output').html('Estou carregando angula coisa…');
var deferred = $.Deferred();

/* Aqui vc define um tempo de notificacao no caso 1 segundo */
timer = setInterval(function() {
    deferred.notify();
}, 1000);

/* Esse timeout simula o tempo de resposta */
setTimeout(function() {
    clearInterval(timer);
    deferred.resolve();
}, 10000);

return deferred.promise();
})().then(function() { 
/* Esse cara é chamado quando termina o processamento assíncrono */
$('#output').html('Terminei de carregar. Agora vou fazer algo!!!'); 
}, null, function() { 
/* Esse cara é notificado a cada segundo enquanto o processamento não for finalizado */
$('#output').html($('#output').html() + '.'); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="output" />

In this example we have a routine that is executed for a certain time. This routine can be compared to loading a page via js. Imagine you need to download a json-shaped file from any page. When you finish you will need to perform something. There is the possibility that you can perform the synchronous treatment, but the message below may occur that can change from browser to browser.

When to use?

You should use whenever a system routine is handled asynchronously and you need to return the page to perform a specific treatment. For example, in the load of an image via js or even in the load of other js that needs to be asynchronous.

    
26.10.2015 / 18:28