Javascript file attached via Drupal behaviours does not work occasionally I'm facing a weird issue where a JS file attached via the Javascript API does not work properly. I couldn't really pin down why it isn't working by the JS file consists of a few event listeners which get attached to DOM elements and it looks like this:
(function ($, Drupal) {
  Drupal.behaviors.basics = {
    attach: function (context, settings) {
      if (context !== document) {
        return;
      }

     initPublicationsAccordion($)
     initBackground($)
     initNavbarFix($)
     initMobileNav($)
     initAuthorsDropdown($)
     setTimeout(() =&gt; initCarousel($), 500) // this fixes it
    }
  };
})(jQuery, Drupal);

and the corresponding *.libraries.yml file:
global:
  css:
    theme:
      css/main.css: {}
  dependencies:
    - core/drupal
    - core/jquery
    - drulma/bulma
    - drulma/mainjs

...
mainjs:
  js:
    js/main.js: {}
  dependencies:
    - core/drupal

There are no errors in the console, but I noticed I can make it work by wrapping the functions in a setTimeout. I would appreciate if anyone has an idea?
You are firing your event on document context, which happens only once (basically same as old school $(document).ready()). But a major point Drupal behaviors is that they are fired every time when somehing is added to the DOM, even when added with Ajax. (core's  BigPipe might add blocks with Ajax, this module is enabled by default)
So instead of the one-shot
  Drupal.behaviors.basics = {
    attach: function (context, settings) {
      if (context !== document) {
        return;
      }
      ...do stuff

target the specific DOM nodes, e.g. if your carousel has a container
&lt;div class=&quot;my_fancy_carousel&quot;&gt;...&lt;/div&gt;
attach the behavior to its class:
  Drupal.behaviors.my_fancy_carousel  {
    attach: function (context, settings) {
      $('.my_fancy_carousel', context).once('init_my_fancy_carousel').each( function() {
        ...do stuff...

Also notice the .once('my_unique_identifier') part which makes sure your functions don't trigger repeatly on the same DOM node