Skip to main content
ajabon grinsmith
Community Expert
Community Expert
October 16, 2025
Answered

ScriptUI: Improvement of the problem that the event was executed twice

  • October 16, 2025
  • 1 reply
  • 92 views

The following is a simplified version of the ScriptUI code I am working on.

var win = new Window("dialog{\
e:EditText{characters: 4, text:'0'}}");

win.e.addEventListener ("keydown", function(e){
    if(e.keyName == "Up"){
        var num = this.text - 0;
        this.text = ++num;
    }
});

win.show();

EditText aims to allow you to enter text freely as usual, and if the text is a number, press the UP ARROW on the keyboard to add 1.

However, when I execute this code, 2 will be added when I press theUP ARROW.

 

What I tried.

Insert “e.stopPropagation();”  ...There was no change in the result.

Insert “e.preventDefault();”  ...The point where 2 is added at a time has improved, but text can no longer be entered.

Insert “$.writeln(e.timeStamp); $.sleep(1000);” ...A timestamp that was offset by 1 second was output.

Change the event to “keyup” ...The event handler is now executed 3 times (I'm laughing).

 

Is there a good solution?

Regards.

Correct answer ajabon grinsmith

Sorry, I asked ChatGPT. The cause is vague, but it's solved..

// Create a local variable for a timestamp
var lastTime = 0;

var win = new Window("dialog{\
e:EditText{characters: 4, text:'0'}}");

win.e.addEventListener ("keydown", function(e){
    var now = new Date().getTime();
    if (now - lastTime < 50) return; // 50ms
    lastTime = now;
    if(e.keyName == "Up"){
        var num = this.text - 0;
        this.text = ++num;
    }
});

win.show();

 Thank you, Mr. Code, who was used as an AI source.

1 reply

ajabon grinsmith
Community Expert
ajabon grinsmithCommunity ExpertAuthorCorrect answer
Community Expert
October 16, 2025

Sorry, I asked ChatGPT. The cause is vague, but it's solved..

// Create a local variable for a timestamp
var lastTime = 0;

var win = new Window("dialog{\
e:EditText{characters: 4, text:'0'}}");

win.e.addEventListener ("keydown", function(e){
    var now = new Date().getTime();
    if (now - lastTime < 50) return; // 50ms
    lastTime = now;
    if(e.keyName == "Up"){
        var num = this.text - 0;
        this.text = ++num;
    }
});

win.show();

 Thank you, Mr. Code, who was used as an AI source.