Class: DelayExecutioner

Inherits:
Object
  • Object
show all
Defined in:
lib/vimamsa/util.rb

Overview

Execute proc after wait_time seconds after last .run call. Used for image scaling after window resize

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(wait_time, _proc) ⇒ DelayExecutioner

Returns a new instance of DelayExecutioner.



229
230
231
232
233
234
235
236
# File 'lib/vimamsa/util.rb', line 229

def initialize(wait_time, _proc)
  @wait_time = wait_time
  @proc = _proc
  @lastt = Time.now
  @thread_running = false
  @last_run = nil
  @wait_before_next = 0
end

Instance Attribute Details

#last_runObject

Returns the value of attribute last_run.



212
213
214
# File 'lib/vimamsa/util.rb', line 212

def last_run
  @last_run
end

#wait_before_nextObject

Returns the value of attribute wait_before_next.



212
213
214
# File 'lib/vimamsa/util.rb', line 212

def wait_before_next
  @wait_before_next
end

Class Method Details

.exec(id:, wait:, callable:) ⇒ Object

Run ‘callable.call’ if ‘wait’ time elapsed from last exec call for this id



214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/vimamsa/util.rb', line 214

def self.exec(id:, wait:, callable:)
  @@h ||= {}
  h = @@h
  if h[id].nil?
    h[id] = DelayExecutioner.new(wait, callable)
  end
  o = h[id]
  if !o.last_run.nil?
    # if Time.now - o.last_run < o.wait_before_next
    # return
    # end
  end
  h[id].run
end

Instance Method Details

#runObject



252
253
254
255
256
257
258
259
260
261
# File 'lib/vimamsa/util.rb', line 252

def run()
  # Reset @lastt to further delay execution until @wait_time from now
  @lastt = Time.now

  # If already executed after last call to run()
  if @thread_running == false
    @thread_running = true
    start_thread
  end
end

#start_threadObject



238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/vimamsa/util.rb', line 238

def start_thread
  Thread.new {
    while true
      sleep 0.1
      if Time.now - @lastt > @wait_time
        @proc.call
        @last_run = Time.now
        @thread_running = false
        break
      end
    end
  }
end