Random Quote Machine, JQUERY EFFECTS, .ajax() and others


Hi Campers!
I’m building my Random Quote Machine. I’m about half way through the challenge.
What’s NOT done is tweeter part (but I don’t worry about it ATM).
My problem is the lack of control over what is changing on the web page.
The idea was to change colours during the change of a quote. It works, but I’d like the changes to happen in sequence. I want to change colours once, THEN swap the quotes and THEN change the colours again. And the problem is that sometimes I can see the new quote before the first change of colours have finished.
I’ve tried to use {async: false} in .ajax(), but it didn’t help.
I’ll try to make it simple, there should be 3 changes in aequence:

  1. First change of colours.
  2. Getting the new quote and making appropriate changes to the web page (RQM)
  3. Second change of colours.
    The change of quote happens before the first change of colours has finished, but it should be after that.
    What can I do to make it working as I want?


jQuery has a .delay() method that could work well for you here.

For example, this code would change the background color, wait a second, then display the quote text:

  background: random(colors), 
  transition: "background 1s" 
}).delay(1000) // 1000ms to account for css transition: "background 1s" 
  .then(function() {
  // add your quote to the page

More info on .delay() is here: https://api.jquery.com/delay/

As another option, or in addition to the above, $.ajax is thenable, i.e., you can chain a .then() method to do something after the ajax success function runs:

// get a quote
  url: "https:// some quote api url",
  // add other ajax parameters as needed before your success function
  success: function(data) {
    // add the quote from the API to the page
}).then(function() { // this function runs after the success function above
  $("body").css("background", "red");

You could also try an implementation with setTimeout() but that could get tricky since you’ll never know how long it takes to get a quote from an API: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout


Thanks a lot! It really helped me. On the web site I was using there was nothing (at least I didn’t see it) about .delay() or .promise() or .then()
My RQM starts working as I expected.
To be honest, even on the web site you provided, is hard to find info about .then().