+ 1

jQuery, change text after time (loop problem)

Hello sololearn people! I am a bit stuck. Maybe one of you can help me. I want to make a jQuery script that changes the messages on my website after a certain amount of time. After it runs out of messages it should start over with the first message (loop). I stored the messages inside an array and it kinda works but only one time (it doesn't loop), thats the problem. I use the shift() method, maybe it wasn't the best choice. Here is the code: function nextMsg() { if (messages.length == 0) { // once there is no more message, I don't know how to start the script over (loop it) so it starts again with the first message } else { // change content of message, fade in, wait, fade out and continue with next message $('#message').html(messages.shift()).fadeIn(500).delay(1000).fadeOut(500, nextMsg); } }; // list of messages to display var messages = [ "Hello!", "Hola!", "Bonjour!", "Hallo!", "Zdravo!" ] // initially hide the message $('#message').hide(); // start animation nextMsg();

29th Jan 2018, 9:07 AM
Mutabor Lingua
2 Réponses
0
function loopMessages(){ var i = 0, max = messages.length-1, loop = setInterval(()=>{ $('#message').html(messages[i]).fadeIn(500).delay(1000).fadeOut(500,()=>{}); i = i === max ? 0 : i+1; }, 1000); // all 1000 milliseconds return ()=>{ clearInterval(loop); } } const clearLoop = loopMessages(); // to stop the loop, call the function that is returned (this technique is called 'closure') clearLoop();
29th Jan 2018, 1:23 PM
Draphar
0
Couldn't get it up and running your way so I solved it with a recursion: (function($) { var taglines = ['Hello!', 'Hola!', 'Bonjour!', 'Zdravo!'], i = 0 interval = 3000, $txt = $('#txt'); $txt.text(taglines[i%taglines.length]); function recursion(){ $txt.fadeOut('400', function() { $(this).text(taglines[i%taglines.length]).fadeIn('400'); }); i++; setTimeout(function(){ recursion(); }, interval); }; setTimeout(recursion, interval) })( jQuery );
29th Jan 2018, 9:45 PM
Mutabor Lingua