简体   繁体   中英

Javascript alert messages and program flow

I have a problem with my function. I want the fireworks to start when the highscore is cracked (before the alert is displayed). Instead, it is currently the case that the alerts are displayed first and then the fireworks are started in the main menu. In the main menu I would like to have finished it again. Only if the player reads through the alert that the highscore was cracked, the fireworks should also be played. If the player clicks on Ok and thus reaches the main menu, it should be finished again. Does anyone have an idea how I can implement this? Enclosed you will find my JavaScript code.

let klick = 0;

display = document.querySelector('#time');

$("#start").click(function() { //clickfunktion beim starten.
  $("#start").fadeToggle(); //Der Startbutton geht weg
  $("#welcome").fadeToggle(); // Das Willkommensschild geht weg
  $("#zeitauswahl").fadeToggle(); //Die Auswahl der Sekunden verschwindet

  $("#time").fadeToggle(900); //Timer kommt 
  $("#clicker").animate({
    height: 'toggle' //inverse aktion...keine height --> klappt auf // aufgeklappt  ---> macht height weg
  }); //clicker wird gestartet 
    var d = $("#zeitauswahl option:selected").val(); //referenziert auf zeitauswahl und option

  var dauer = parseInt(d); //verwandelt Dauer in einen Int

  startTimer(dauer); //übergibt die variable dauer, und die Funktion wird gestartet.  
})

function startTimer(dauer) {
    let timer = parseInt(dauer);
  runTimer();
  zeit = setInterval(runTimer, 1000); //zahl gibt an, wie oft die Function pro zeit wiederholt wird. Hier eine Sekunde (1000Millisekunden)
  function runTimer(){
    display.textContent = parseInt(timer); // zeigt sekunden-variable

    --timer; //setzt den timer immer einen herab

    if (timer < 0.00) {

      timer = 5;
      console.log(timer); //debug info
      $("#start").fadeToggle();
      $("#welcome").fadeToggle();
      $("#zeitauswahl").fadeToggle();
      $("#time").fadeToggle();
      $("#clicker").fadeToggle();
      $("#clicker").css("margin-top", "10%");
      $("#clicker").css("margin-left", "50%");

      alert("Sauber du hast " + klick + " klicks in 5 Sekunden geschafft!");
      alert('High Score ist ' + highScore(klick)); // zeigt den HighScore

      klick = 0
      console.log(timer);

      clearInterval(zeit);

    } //wenn timer auf 0 ist, wird alles wieder angezeigt und die Interval-Function beendet

}


};

$("#clicker").click(function() {
  let zufall = Math.floor(Math.random() * 400) -200 //setzt eine zufällige höhe für den clicker
  let zufal = Math.floor(Math.random() * 450) //Zufällige Variable für den Linkswert

  klick = klick + 1 //setzt den zähler beim klicken eins hoch
  if (klick % 2 == 0) {
    $("#clicker").animate({
      opacity: '0.3', //macht den klicker leicht durchsichtig
      left: zufall + "px",
      top: zufal + "px"
    }, "fast"); //bewegt den Klick-Block auf eine zufällige Stelle
  } else {
    $("#clicker").animate({
      opacity: '1.0',  //macht den Klicker sichtbar
      left: zufall + "px",
      top: zufal + "px"
    }, "fast")

  }



});

var fireworks = {

  ///////////////////////////// configuration ////////////////////////////

  // random colors
  _color: ['#D0D0D0', '#FF0000', '#FFFF00', '#22FF00', '#2040FF', '#00CCFF', '#FF00FF', '#A319D6'],
  // gravity factor
  _gravity: 0.07,
  // air resistance factor
  _resistance: 0.975,
  // zIndex of particles
  _zIndex: 20000,
  // maximal age of particles (in msec)
  _maxAge: 2000,
  // interval of appearing explosions (in msec)
  _interval: [500, 2500],
  // amount of particles per explosion
  _particlesPerExplosion: 40,
  // maximal speed of particle at moment of explosion
  _speed: 5,
  // minimal/maximal size of particle
  _minSize: 8,
  _maxSize: 12,



  ///////////////////////////// private vars /////////////////////////////

  _particles: [],
  _bodyWidth: 0,
  _bodyHeight: 0,
  _count: 0,
  _lastInterval: 0,



  ////////////////////////////// functions ///////////////////////////////

  // init fireworks
  init: function()
  {
    this._addEventListener(window, 'resize', function() { return fireworks.resize.apply(fireworks); });
    this._addEventListener(window, 'load', function() { return fireworks.start.apply(fireworks); });
  },


  // add an event listener
  _addEventListener: function(el, name, handler)
  {
    if (el.addEventListener)
      el.addEventListener(name, handler, false); 
    else if (el.attachEvent)
      el.attachEvent('on' + name, handler);
  },


  // start fireworks
  start: function()
  {
    // init window size
    this.resize();

    // start to move particles
    this._animFn = function() {fireworks._move();};
    this._lastInterval = this._time();
    requestAnimFrame(this._animFn);

    this._addExplosion();
  },


  // get current time
  _time: function()
  {
    return +new Date();
  },


  // return a random integer
  _random: function(value)
  {
    return Math.random() * value;
  },


  // return a random array element
  _randomArray: function(arr)
  {
    return arr[
      Math.floor(
        Math.random() * (arr.length)
      )
    ];
  },


  // add a new explosion
  _addExplosion: function()
  {
    var x = Math.floor(this._random(this._bodyWidth)),
      y = Math.floor((this._random(.5) + .1) * this._bodyHeight),
      dx = this._random(10) - 5,
      dy = this._random(-2) - 1,
      c1 = this._randomArray(this._color),
      c2 = this._randomArray(this._color);

    for (var i = 0; i < this._particlesPerExplosion; i++)
    {
      this._createParticle(
        x,
        y,
        dx,
        dy,
        i / (this._particlesPerExplosion - 1) * 180 * Math.PI,
        this._random(this._speed),
        this._random(1) > .5 ? c1 : c2
      );
    }

    window.setTimeout(
      function() { return fireworks._addExplosion.apply(fireworks);},
      this._random(this._interval[1] - this._interval[0]) + this._interval[0]
    );
  },


  // creates a new particle
  _createParticle: function(x, y, dx, dy, rot, speed, color)
  {
    var el = null,
      foundEl = false,
      p = this._particles;

    // look for old particle
    for (var i = 0, l = p.length; i < l; i++)
      if (p[i].data.age > 1)
      {
        el = p[i];
        foundEl = true;
        break;
      }

    // create span child for particles
    if (!foundEl)
    {
      el = document.createElement('div');
      el.className       = 'particle';
      el.style.position  = 'absolute';
      el.style.fontSize  = this._maxSize + 'px';
      el.style.zIndex    = this._zIndex;
      el.style.width     = this._maxSize + 'px';
      el.style.textAlign = 'center';
      el.style.overflow  = 'hidden';
      el.innerHTML       = '&#x25cf;';
    }

    el.style.left  = x + 'px';
    el.style.top   = y + 'px';
    el.style.color = color;
    el.data = {
      x: x,
      y: y,
      dx: Math.cos(rot) * speed + dx,
      dy: Math.sin(rot) * speed + dy,
      color: color,
      age: Math.random() * .25
    };

    if (!foundEl)
    {
      document.getElementsByTagName('body')[0].appendChild(el);
      this._particles.push(el);
    }
  },


  // move existing particles
  _move: function()
  {
    requestAnimFrame(this._animFn);

    // calculate movement factor
    var dif = this._time() - this._lastInterval;
    this._lastInterval = this._time();

    var delta = dif / 20,
      el,
      d,
      p = this._particles,
      r = Math.pow(this._resistance, delta),
      g = this._gravity * delta,
      a = dif / this._maxAge;

    for (var i = 0, l = p.length; i < l; i++)
    {
      el = p[i];
      d = el.data;

      if (d.age > 1)
        continue;

      d.age += a;
      d.dy += g;
      d.dx *= r;
      d.dy *= r;
      d.x += d.dx * delta;
      d.y += d.dy * delta;

      if (d.x < 0)
      {
        d.dx *= -1;
        d.x = 0;
      }
      else if (d.x > this._bodyWidth)
      {
        d.dx *= -1;
        d.x = this._bodyWidth;
      }
      if (d.y < 0)
      {
        d.dy *= -1;
        d.y = 0;
      }
      else if (d.y > this._bodyHeight)
      {
        d.dy *= -1;
        d.y = this._bodyHeight;
      }

      if (d.age > 1)
        d.x = d.y = 0;

      el.style.left = d.x + 'px';
      el.style.top = d.y + 'px';
      el.style.color = (Math.random() * .5 + d.age >= 1) ? 'transparent' : d.color;
      el.style.fontSize = Math.max(this._minSize, (1 - d.age) * this._maxSize) + 'px';
    }
  },


  // calculate new positions for all particles
  resize: function()
  {
    // get new width and height
    this._bodyWidth = this._getWindowWidth() - this._maxSize;
    this._bodyHeight = this._getWindowHeight() - this._maxSize - 10;
  },


  // get window width
  _getWindowWidth: function()
  {
    return document.getElementsByTagName('body')[0].offsetWidth;
  },


  // get window height
  _getWindowHeight: function()
  {
    var h = Math.max(self.innerHeight || 0, window.innerHeight || 0);

    if (document.documentElement)
      h = Math.max(h, document.documentElement.clientHeight || 0);
    if (document.body)
    {
      h = Math.max(h, document.body.clientHeight || 0);
      h = Math.max(h, document.body.scrollHeight || 0);
      h = Math.max(h, document.body.offsetHeight || 0);
    }

    return h;
  }

};

// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
      window.webkitRequestAnimationFrame || 
      window.mozRequestAnimationFrame    || 
      window.oRequestAnimationFrame      || 
      window.msRequestAnimationFrame     || 
      function (cb){
      window.setTimeout(cb, 1000 / 60);
      };
})();



function highScore(score) {
  var saved = 0;

  saved = parseFloat(localStorage.getItem('highScore')) || 0; //nimmt zeichenketten Argument (highscore) und gibt Float. highscore oder 0
  score = parseFloat(score) || 0; 
  document.getElementById("highscore").innerHTML = saved;

  if (score > saved) {
    saved = score; //speichert neuen Highscore, wenn der score größer ist als die gespeicherte variable
    localStorage.setItem('highScore', score);//speichert highscore im browser
    fireworks.start();
  }
  return saved;

}

Since your code is quite complicated I will provide general instructions only. jQuery recently became compliant with promises. Promises will let you arrange execution in order. Here's an example.

$.when($("span").fadeIn()).done(function() {
   $.when($("span").fadeOut()).done(function() {
        alert("done!")
   });
});

A Layman translation of the code is: When the fadeIn is done, then fadeOut, and when fadeOut is done, alert "done!".

This way you can ensure the correct order of execution. Resting in timers is not a good idea for that kind of logic.

The problem is that javascript alerts are "modal", so they freeze the javascript until you click them. They don't play nice.

Here is a simple solution to replace alerts with something more gentle.

 $('.mybutt').click(function(){ var tmp = this.id; var txt = $(this).text(); $('#msgbox').text(txt).show(); setTimeout( function(){$('#msgbox').fadeOut() },1500); }); 
 .mybutt{display:inline-block;margin-left:10px;} .mybutt{border:1px solid dodgerblue;padding:3px 7px;cursor:pointer;} #msgbox{position:absolute;top:10%;left:30%;padding:20px;display:none;} #msgbox{border:1px solid orange;background:wheat;} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <div id="btn_1" class="mybutt">One</div> <div id="btn_2" class="mybutt">Two</div> <div id="msgbox"></div> 

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