• Hi,

    I am a relatively new user of the Bangle.js. I was playing around with the button and touch functionality of the watch in the emulator.
    I am trying to declare a global variable inside of a function. I am aware that the way to do this in JavaScript is to prepend the variable declaration with the word 'window', like below:
    window.a = 'abc';

    When I try to do the same inside my code, it is giving me an "Uncaught ReferenceError: "window" is not defined" error message.

    Am I missing something here? I have uploaded my code snippet for reference.

    // Load fonts
    require("Font7x11Numeric7Seg").add(Graphics);
    var IOString = "No Input";
    function draw() {
      var d = new Date(), h = d.getHours(), m =
      d.getMinutes();
      var time = (" "+h).substr(-2) + ":" + ("0"+m).substr(-2);
      g.clear();
      g.setFont("7x11Numeric7Seg",4);
      g.setFontAlign(1,1); // align right bottom
      g.drawString(time, 160, 140, true /*clear background*/);
      g.setFont("7x11Numeric7Seg",2);
      g.drawString(("0"+d.getSeconds()).substr(-2), 190, 140, true);
      g.setFont("6x8");
      g.drawString(IOString, 70, 185, true); // draw the input
      window.a = 'abc';
    }
    
    var secondInterval = setInterval(draw, 100);
    setWatch(() => {
      IOString = "Button 1";
    }, BTN1, {repeat: true});
    setWatch(() => {
      IOString = "Button 2";
    }, BTN2, {repeat: true, edge: "falling"});
    setWatch(() => {
      IOString = "Button 3";
    }, BTN3, {repeat: true});
    Bangle.on('swipe', (sDir) => {
      if (sDir==1) {
        window.secondInterval = setInterval(draw, 100);
        IOString = "Swipe left";
      } else {
        IOString = "Swipe right";
        clearInterval(secondInterval);
        g.clear();
        g.drawString(IOString, 120, 120);
      }
    });
    Bangle.on('touch', (sDir) => {
      if (sDir==1) {
        IOString = "Touch left";
      } else {
        IOString = "Touch right";
      }
    });
    

    I would like to set my secondInterval variable to be a global one, so that it can be cleared from outside the function where it is defined.

    Any help would be greatly appreciated.

  • window is web browser window when javascript runs as part of web page, do you really expect web browser to be runing inside the watch? try global
    see also https://javascript.info/global-object , it is same like in node.js

  • Ah yes! I got confused between the usage. Tried out using global and that works perfectly as expected.

    Thanks for your help! :D

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Is there a way to define a global variable inside a function in Bangle.js?

Posted by Avatar for newLearner @newLearner

Actions